package com.cardmanager.pro.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.cardmanager.pro.authorization.CreditCardManagerAuthorizationHandle;
import com.cardmanager.pro.business.ConsumeTaskPOJOBusiness;
import com.cardmanager.pro.business.CreditCardAccountBusiness;
import com.cardmanager.pro.business.CreditCardAccountHistoryBusiness;
import com.cardmanager.pro.business.CreditCardManagerConfigBusiness;
import com.cardmanager.pro.business.RepaymentTaskPOJOBusiness;
import com.cardmanager.pro.executor.BaseExecutor;
import com.cardmanager.pro.executor.ConsumeExecutor;
import com.cardmanager.pro.executor.RepaymentExecutor;
import com.cardmanager.pro.pojo.ConsumeTaskPOJO;
import com.cardmanager.pro.pojo.ConsumeTaskVO;
import com.cardmanager.pro.pojo.CreditCardAccount;
import com.cardmanager.pro.pojo.CreditCardManagerConfig;
import com.cardmanager.pro.pojo.RepaymentTaskPOJO;
import com.cardmanager.pro.pojo.RepaymentTaskVO;
import com.cardmanager.pro.util.CardConstss;
import com.cardmanager.pro.util.RestTemplateUtil;

import cn.jh.common.tools.ResultWrap;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.ExceptionUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class CreditCardManagerTaskService {

	private final Logger LOG = LoggerFactory.getLogger(getClass());

	@Autowired
	private RestTemplateUtil util;
	
	@Autowired
	private CreditCardAccountBusiness creditCardAccountBusiness;
	
	@Autowired
	private CreditCardAccountHistoryBusiness creditCardAccountHistoryBusiness;
	
	@Autowired
	private CreditCardManagerConfigBusiness creditCardManagerConfigBusiness;
	
	@Autowired
	private RepaymentExecutor repaymentExecutor;
	
	@Autowired
	private ConsumeExecutor consumeExecutor;
	
	@Autowired
	private RepaymentTaskPOJOBusiness repaymentTaskPOJOBusiness;
	
	@Autowired
	private ConsumeTaskPOJOBusiness consumeTaskPOJOBusiness;
	
	@Autowired
	private CreditCardManagerAuthorizationHandle creditCardManagerAuthorizationHandle;
	
	@Autowired
    private RedisTemplate redisTemplate;
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private BaseExecutor baseExecutor;
	/**
	 * 前端调用   查询用户费率/手续费接口
	 * @param request
	 * @param userId
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/query/rate/by/userid")
	public @ResponseBody Object getChannelRateByUserId(HttpServletRequest request,
			@RequestParam("userId")String userId,
			@RequestParam("brandId")String brandId,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object> map = new HashMap<>();
		Map<String, Object> userChannelRate = getUserChannelRate(userId,brandId.trim(),version);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase((String) userChannelRate.get(CommonConstants.RESP_CODE))){
			return userChannelRate;
		}
		JSONObject resultJSONObject = (JSONObject) userChannelRate.get(CommonConstants.RESULT);
		String rateStr = resultJSONObject.getString("rate");
		String extraFeeStr = resultJSONObject.getString("extraFee");
		String withdrawFeeStr = resultJSONObject.getString("withdrawFee");
		BigDecimal serviceCharge = new BigDecimal(extraFeeStr).add(new BigDecimal(withdrawFeeStr)).setScale(2, BigDecimal.ROUND_UP);;
		BigDecimal rate = new BigDecimal(rateStr).setScale(4, BigDecimal.ROUND_UP);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功!");
		map.put("serviceCharge", serviceCharge);
		map.put("rate", rate);
		return map;
	}
	
	/**
	 * 前端调用	生成前端展示的临时任务
	 * @param request
	 * @param suserId
	 * @param creditCardNumber
	 * @param strExecuteDates
	 * @param amount
	 * @param brandId
	 * @param scount
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/create/temporary/plan")
	public @ResponseBody Object generationTemporaryPlan(HttpServletRequest request,
			@RequestParam(value = "userId") String suserId,
			@RequestParam(value = "creditCardNumber") String creditCardNumber,
			@RequestParam(value = "executeDate") String[] strExecuteDates, 
			@RequestParam(value = "amount") String amount,
			@RequestParam(value= "brandId")String brandId,
			@RequestParam(value = "count") String scount,
			@RequestParam(value = "version",required=false,defaultValue="1") String version){
		int number = 10;
		amount = amount.trim();
		scount = scount.trim();
		suserId = suserId.trim();
		creditCardNumber = creditCardNumber.trim();
		
		int repaymentCountLimit = 0;
		int consumeSingleMoneyLimit = 0;
		int consumeCountLimit =0;
		String consumeChannelId = null;
		String repaymentChannelId = null;
		String consumeChannelTag = null;
		String repaymentChannelTag = null;
		
//		根据brandId查找配置信息
		CreditCardManagerConfig creditCardManagerConfig = creditCardManagerConfigBusiness.findByVersion(version);
		if(creditCardManagerConfig!=null){
//			消费配置信息
			consumeSingleMoneyLimit = creditCardManagerConfig.getConSingleLimitMoney().intValue();
			consumeCountLimit = creditCardManagerConfig.getConSingleLimitCount();
			consumeChannelId = creditCardManagerConfig.getChannelId();
			consumeChannelTag = creditCardManagerConfig.getChannelTag();
//			还款配置信息
			repaymentCountLimit = creditCardManagerConfig.getPaySingleLimitCount();
			repaymentChannelId = creditCardManagerConfig.getChannelId();
			repaymentChannelTag = creditCardManagerConfig.getChannelTag();
			int createOnOff = creditCardManagerConfig.getCreateOnOff();
			if (1 != createOnOff) {
				return ResultWrap.init(CommonConstants.FALIED, "该还款通道正在维护中,请使用其他还款通道!");
			}
		}else {
			return ResultWrap.init(CommonConstants.FALIED, "该还款通道正在维护中,请使用其他还款通道!");
		}
		
		Map<String, Object> map = new HashMap<>();
//		验证是否有批量生成的未执行计划
		boolean doesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO(suserId, creditCardNumber,version);
		boolean doesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO(suserId, creditCardNumber,version);
		if(doesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO || doesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您有未执行计划,请等待任务执行完后再生成计划!");
			return map;
		}
//		验证是否有首笔验证的已完成执行计划
//		null 没有 !null 有
		ConsumeTaskPOJO firstConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveOrderStatus1AndTaskType0ConsumeTaskPOJO(suserId, creditCardNumber,version);
//		null 没有 !null 有
		RepaymentTaskPOJO firstRepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveOrderStatus1AndTaskType0RepaymentTaskPOJO(suserId, creditCardNumber,version);
		if(firstConsumeTaskPOJO == null || firstRepaymentTaskPOJO == null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您未完成首笔验证,请等待计划执行完后再生成计划!");
			return map;
		}
//		验证日期格式是否正确
		Date[] executeDates = new Date[strExecuteDates.length];
		try {
			for(int i= 0;i < strExecuteDates.length;i++){
				executeDates[i] = DateUtil.getDateStringConvert(new Date(), strExecuteDates[i],"yyyy-MM-dd");
			}
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:选择日期格式有误,正确格式为:2000-01-01");
			return map;
		}
//		获取用户账单日和还款日
		CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(suserId, creditCardNumber,version);
		Integer billDate = creditCardAccount.getBillDate();
		Integer repaymentDate = creditCardAccount.getRepaymentDate();
		BigDecimal creditBlance = creditCardAccount.getCreditBlance();
		
		Date dateNow = DateUtil.getDateStringConvert(new Date(), DateUtil.getDateStringConvert(new String(),new Date() ,"yyyy-MM-dd"), "yyyy-MM-dd");
		dateNow = new Date(dateNow.getTime() + 24*60*60*1000);
		Integer executeDay = 0;
//		验证日期是否是今天以后
		for(int i = 0;i < executeDates.length;i++){
			if(dateNow.getTime() > executeDates[i].getTime() ){
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "只能选择今天以后的日期,请重新选择!");
				return map;
			}
//			如果有选择账单日和还款日,则验证任务执行日期是否在账单日之后还款日之前
			if(billDate!=0 && repaymentDate!=0){
				executeDay = Integer.valueOf(DateUtil.getDateStringConvert(new String(),executeDates[i] ,"dd"));
				if(billDate > repaymentDate){
					if(!((billDate <= executeDay)||(repaymentDate >= executeDay))){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "执行任务的日期只能为账单日之后还款日之前,请在该日期之间进行选择");
						return map;
					}
				}else{
					if(!((billDate <= executeDay)&&(repaymentDate >= executeDay))){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "执行任务的日期只能为账单日之后还款日之前,请在该日期之间进行选择");
						return map;
					}
				}
			}
		}
		
		// 还款笔数验证
		int count;
		try {
			count = Integer.valueOf(scount);
		} catch (NumberFormatException e1) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "还款笔数输入不正确,请重新输入!");
			return map;
		}
		if(!(count!=0 && count >= strExecuteDates.length && count <= strExecuteDates.length*repaymentCountLimit)){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:选择的日期所对应的还款笔数应大于等于"+strExecuteDates.length + "笔而且小于等于" + strExecuteDates.length*repaymentCountLimit +"笔");
			return map;
		}
//		金额验证
		BigDecimal totalAmount;
		try {
			totalAmount = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_UP);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您输入的金额有误,请重新输入!");
			return map;
			
		}
//		总金额验证
		BigDecimal perAveCountAmount = totalAmount.divide(new BigDecimal(scount),2,BigDecimal.ROUND_HALF_DOWN);
		if (perAveCountAmount.compareTo(new BigDecimal(consumeSingleMoneyLimit * consumeCountLimit + number)) < 0) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:当前金额可生成计划笔数为:" + (Integer.valueOf(amount.substring(0, amount.indexOf(".")==-1?amount.length():amount.indexOf(".")))/(consumeSingleMoneyLimit * consumeCountLimit + number))+ "笔");
			return map;
		}
//		信用卡验证
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("user", "error url request");
		String url = uri.toString() + "/v1.0/user/bank/verify/isuseable";
		LinkedMultiValueMap<String,String> requestEntity = new LinkedMultiValueMap<String,String>();
		requestEntity.add("userId", suserId);
		requestEntity.add("bankCardNumber", creditCardNumber);
		String resultString = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject resultJSONObject = JSONObject.fromObject(resultString);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase(resultJSONObject.getString(CommonConstants.RESP_CODE))){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, resultJSONObject.getString(CommonConstants.RESP_MESSAGE).isEmpty()?"生成计划失败,原因:该卡不可用,请更换一张信用卡!":resultJSONObject.getString(CommonConstants.RESP_MESSAGE));
			return map;
		}
		
		JSONObject bankInfoJSON = resultJSONObject.getJSONObject(CommonConstants.RESULT);
		String bankName = bankInfoJSON.getString("bankName");
//		查询用户费率
		Map<String, Object> userChannelRate = getUserChannelRate(suserId,brandId.trim(),version);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase((String) userChannelRate.get(CommonConstants.RESP_CODE))){
			return userChannelRate;
		}
		
		resultJSONObject = (JSONObject) userChannelRate.get(CommonConstants.RESULT);
		String rateStr = resultJSONObject.getString("rate");
		String extraFeeStr = resultJSONObject.getString("extraFee");
		String withdrawFeeStr = resultJSONObject.getString("withdrawFee");
//		单笔还款手续费
		BigDecimal serviceCharge = new BigDecimal(extraFeeStr).add(new BigDecimal(withdrawFeeStr)).setScale(2, BigDecimal.ROUND_UP);;
//		费率
		BigDecimal rate = new BigDecimal(rateStr).setScale(4, BigDecimal.ROUND_UP);;
		
		// 减去每笔最低金额剩余总金额
//		BigDecimal scale = perAveCountAmount.divide(new BigDecimal((consumeSingleMoneyLimit * consumeCountLimit + number)),2,BigDecimal.ROUND_DOWN).setScale(0, BigDecimal.ROUND_DOWN);
//		BigDecimal surplusCountAmount = totalAmount.subtract(new BigDecimal(consumeSingleMoneyLimit * consumeCountLimit).multiply(new BigDecimal(count)).multiply(scale));
		BigDecimal surplusCountAmount = null;
		
		surplusCountAmount = totalAmount.multiply(BigDecimal.valueOf(0.1)).setScale(0, BigDecimal.ROUND_DOWN);
		BigDecimal preAvgAmount = totalAmount.subtract(surplusCountAmount).divide(BigDecimal.valueOf(count),0,BigDecimal.ROUND_DOWN);
		BigDecimal pointAmount = totalAmount.subtract(surplusCountAmount).subtract(preAvgAmount.multiply(BigDecimal.valueOf(count)));
		
		int max = surplusCountAmount.divide(BigDecimal.valueOf(count),0,BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(1)).intValue();
		int min = surplusCountAmount.divide(BigDecimal.valueOf(count),0,BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(0.8)).intValue();
		
		// 减去一笔还款中最低消费总金额剩余一笔还款的金额
		BigDecimal surplusSubCountAmount = null;
		// 随机每笔金额
		BigDecimal randomCountAmount = BigDecimal.ZERO;
		// 随机每次消费金额
		BigDecimal randomSubCountAmount = BigDecimal.ZERO;
		// 执行任务日期
		BigDecimal[][] perCountAmount = new BigDecimal[count][consumeCountLimit+1];
		
		Random random = new Random();
		// 分配每笔还款的金额
		for (int i = 0; i < count; i++) {
			int result = min + (int)(Math.random() * ((max - min)+1));
			if (i != count - 1) {
				if(surplusCountAmount.compareTo(BigDecimal.ZERO)>0){
					randomCountAmount = new BigDecimal(result);
					surplusCountAmount = surplusCountAmount.subtract(randomCountAmount);
					perCountAmount[i][0] = preAvgAmount.add(randomCountAmount);
				}else{
					perCountAmount[i][0] = preAvgAmount;
				}
			} else {
				perCountAmount[i][0] = preAvgAmount.add(surplusCountAmount).add(pointAmount);
			}
			
			
			
//			System.out.println("perCountAmount=============:" + perCountAmount[i][0]);
			surplusSubCountAmount = perCountAmount[i][0].subtract(new BigDecimal(consumeCountLimit*consumeSingleMoneyLimit));
			// 分配每笔还款的消费任务金额
			for (int j = 0; j < consumeCountLimit; j++) {
				if(j != consumeCountLimit-1){
//					System.out.println("surplusSubCountAmount====:"+surplusSubCountAmount);
					if(surplusSubCountAmount.compareTo(BigDecimal.ZERO)>0){
						int max2 = surplusSubCountAmount.multiply(BigDecimal.valueOf(0.6)).intValue();
						int min2 = surplusSubCountAmount.multiply(BigDecimal.valueOf(0.4)).intValue();
						result = min2 + (int)(Math.random() * ((max2 - min2)+1));
						randomSubCountAmount = new BigDecimal(result);
						surplusSubCountAmount = surplusSubCountAmount.subtract(randomSubCountAmount);
						perCountAmount[i][j+1] = new BigDecimal(consumeSingleMoneyLimit).add(randomSubCountAmount);
					}else{
						perCountAmount[i][j+1] = new BigDecimal(consumeSingleMoneyLimit);
					}
				}else{
					perCountAmount[i][j+1] = new BigDecimal(consumeSingleMoneyLimit).add(surplusSubCountAmount);
				}
				
				if(CardConstss.CARD_VERSION_1.equals(version)){
					if(perCountAmount[i][j+1].compareTo(BigDecimal.valueOf(5000)) > 0){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,信用卡单笔消费不能超过5000元,请减少还款金额,或者增加还款天数和笔数再重新生成计划!");
						return map;
					}
					if(bankName!= null && bankName.contains("光大")){
						if(BigDecimal.valueOf(2000).compareTo(perCountAmount[i][j+1]) < 0){
							map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,光大银行信用卡单笔消费不能超过2000元,请减少还款金额,或者增加还款天数和笔数再重新生成计划");
							return map;
						}
					}else if(bankName!= null && bankName.contains("农业") || bankName.contains("招商")){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "抱歉,该银行卡不支持使用此功能,请更换银行卡!");
						return map;
					}
					
				}else if(CardConstss.CARD_VERSION_2.equals(version)){
					if(perCountAmount[i][j+1].compareTo(BigDecimal.valueOf(1000)) > 0){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,信用卡单笔消费不能超过1000元,请减少还款金额,或者减少预留金额百分比再重新生成计划!");
						return map;
					}
					if(bankName!= null && bankName.contains("交通")){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "抱歉,该银行卡不支持使用此功能,请更换银行卡!");
						return map;
					}else if(bankName!= null && (bankName.contains("光大") || bankName.contains("中国银行"))){
						if(BigDecimal.valueOf(400).compareTo(perCountAmount[i][0]) < 0){
							map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,信用卡单日消费不能超过400元,请减少还款金额,或者减少预留金额百分比再重新生成计划");
							return map;
						}
					}
					
				}
			}

		}
		Date nowTime = new Date();
		// 初始化还款任务
		RepaymentTaskVO[] repaymentTaskVOs = new RepaymentTaskVO[count];
		for (int i = 0; i < count; i++) {
			// 对金额进行取角
			repaymentTaskVOs[i] = new RepaymentTaskVO();
			
//			repaymentTaskVOs[i].setConsumeTaskVOs(new ConsumeTaskVO[consumeCountLimit]);
			// 设置userId
			repaymentTaskVOs[i].setUserId(suserId);
			// 设置还款卡号
			repaymentTaskVOs[i].setCreditCardNumber(creditCardNumber);
			// 设置还款通道id
			repaymentTaskVOs[i].setChannelId(repaymentChannelId);
			// 设置还款通道tag
			repaymentTaskVOs[i].setChannelTag(repaymentChannelTag);
			// 设置还款金额
			repaymentTaskVOs[i].setAmount(perCountAmount[i][0]);
			// 设置还款手续费
			repaymentTaskVOs[i].setServiceCharge(serviceCharge);
			// 设置消费费率
			repaymentTaskVOs[i].setRate(rate);
			// 设置总手续费
			BigDecimal totalServiceCharge = repaymentTaskVOs[i].getAmount().add(serviceCharge).setScale(2, BigDecimal.ROUND_UP).divide(BigDecimal.ONE.subtract(rate),2,BigDecimal.ROUND_UP).subtract(repaymentTaskVOs[i].getAmount());
			totalServiceCharge = totalServiceCharge.add(BigDecimal.valueOf(0.01));
			repaymentTaskVOs[i].setTotalServiceCharge(totalServiceCharge);
			// 设置任务描述
			repaymentTaskVOs[i].setDescription("还款计划");
			// 设置创建时间
			repaymentTaskVOs[i].setCreateTime(DateUtil.getDateStringConvert(new String(), nowTime, "yyyy-MM-dd HH:mm:ss"));
		}
		
		//随机分配执行日期
		Date[] executeTime = new Date[strExecuteDates.length];
		for(int i=0;i < strExecuteDates.length;i++){
//			executeTime[i] = DateUtil.getDateFromStr(strExecuteDates[i]); 
			executeTime[i] = DateUtil.getDateStringConvert(new Date(), strExecuteDates[i], "yyyy-MM-dd");
			repaymentTaskVOs[i].setExecuteDate(strExecuteDates[i]);
		}
//		还款笔数和日期的差值,差值笔数将随机分配至各天
		int differencCount = count - strExecuteDates.length;
		int index = 0;
		if (differencCount != 0 && differencCount == strExecuteDates.length) {
			int j = 0;
			for (int i = strExecuteDates.length; i < count; i++){
				repaymentTaskVOs[i].setExecuteDate(strExecuteDates[j]);
				j++;
			}
		}else if(differencCount != 0){
			for (int i = strExecuteDates.length; i < count; i++) {
				index = random.nextInt(strExecuteDates.length);
				if (strExecuteDates[index] != null) {
					repaymentTaskVOs[i].setExecuteDate(strExecuteDates[index]);
					strExecuteDates[index] = null;
				} else {
					for (int j = 0; j < strExecuteDates.length; j++) {
						if (strExecuteDates[j] != null) {
							repaymentTaskVOs[i].setExecuteDate(strExecuteDates[j]);
							strExecuteDates[j] = null;
							break;
						}
					}
				}
			}
		}
		// 随机分配执行时间
		String initTime = null;
		String executeDateTime = null;
		Date initDateTime = null;
		int randomInt = 0;
		for(int i=0;i < count;i++){
			if(i >= strExecuteDates.length){
				if(CardConstss.CARD_VERSION_1.equals(version) || CardConstss.CARD_VERSION_6.equals(version)) {
					initTime = " 16:00:00";
				}else if(CardConstss.CARD_VERSION_2.equals(version)) {
					initTime = " 14:30:00";
				}else if(CardConstss.CARD_VERSION_3.equals(version) || CardConstss.CARD_VERSION_5.equals(version)) {
					initTime = " 15:00:00";
				}else if(CardConstss.CARD_VERSION_4.equals(version)) {
					initTime = " 15:30:00";
				}
			}else{
				initTime = " 09:00:00";
			}
			
			// 设置还款任务id
			repaymentTaskVOs[i].setRepaymentTaskId(repaymentTaskVOs[i].getExecuteDate().replace("-", "")+
					DateUtil.getDateStringConvert(new String(), new Date(),"HHSSS")+ random.nextInt(9)+ random.nextInt(9)+random.nextInt(9)+i+"1");
			// 设置消费子任务字段
			
//			String[] consumeTypeName = {"娱乐","购物","其他","通信","交通","住宿","餐饮"};
			List<String> consumeTypeName = new ArrayList<>();
			consumeTypeName.add("娱乐");
			consumeTypeName.add("购物");
			consumeTypeName.add("其他");
			consumeTypeName.add("通信");
			consumeTypeName.add("交通");
			consumeTypeName.add("住宿");
			consumeTypeName.add("餐饮");
			for (int j = 0; j < consumeCountLimit; j++) {
//				repaymentTaskVOs[i].getConsumeTaskVOs()[j] = new ConsumeTaskVO();
				repaymentTaskVOs[i].getConsumeTaskVOs().add(new ConsumeTaskVO());
//				ConsumeTaskVO consumeTaskVO = repaymentTaskVOs[i].getConsumeTaskVOs()[j];
				ConsumeTaskVO consumeTaskVO = repaymentTaskVOs[i].getConsumeTaskVOs().get(j);
				// 设置userId
				consumeTaskVO.setUserId(suserId);
				// 设置消费通道id
				consumeTaskVO.setChannelId(consumeChannelId);
				// 设置消费通道tag
				consumeTaskVO.setChannelTag(consumeChannelTag);
				// 设置还款任务id
				consumeTaskVO.setRepaymentTaskId(repaymentTaskVOs[i].getRepaymentTaskId());
				// 设置消费卡号
				consumeTaskVO.setCreditCardNumber(creditCardNumber);
				// 设置消费任务
				consumeTaskVO.setDescription("消费计划");
				// 设置消费类型
				randomInt = new Random().nextInt(consumeTypeName.size());
				consumeTaskVO.setConsumeType(consumeTypeName.get(randomInt));
				consumeTypeName.remove(randomInt);
				
				// 设置消费金额
				consumeTaskVO.setAmount(perCountAmount[i][j + 1]);
				if(j == 0){
					consumeTaskVO.setRealAmount(consumeTaskVO.getAmount().add(repaymentTaskVOs[i].getTotalServiceCharge()));
					consumeTaskVO.setServiceCharge(repaymentTaskVOs[i].getTotalServiceCharge());
				}else{
					consumeTaskVO.setRealAmount(consumeTaskVO.getAmount());
				}
				// 设置执行日期
				consumeTaskVO.setExecuteDate(repaymentTaskVOs[i].getExecuteDate());
				// 设置创建时间
				consumeTaskVO.setCreateTime(repaymentTaskVOs[i].getCreateTime());
				// 设置消费子任务id
				consumeTaskVO.setConsumeTaskId(Long.valueOf(repaymentTaskVOs[i].getRepaymentTaskId())+(j+1)+"");
				
				initDateTime = DateUtil.getDateStringConvert(new Date(), consumeTaskVO.getExecuteDate() + initTime, "yyyy-MM-dd HH:mm:ss");
				executeDateTime = DateUtil.getDateStringConvert(new String(),new Date(initDateTime.getTime()+(30*70*1000)+(random.nextInt(60*70*1000))),"yyyy-MM-dd HH:mm:ss");
				// 设置消费子任务执行日期时间
				consumeTaskVO.setExecuteDateTime(executeDateTime);
				initTime = executeDateTime.substring(executeDateTime.indexOf(" "));
			}
			initDateTime = DateUtil.getDateStringConvert(new Date(), repaymentTaskVOs[i].getExecuteDate() + initTime, "yyyy-MM-dd HH:mm:ss");
			executeDateTime = DateUtil.getDateStringConvert(new String(),new Date(initDateTime.getTime()+(30*70*1000)+(random.nextInt(60*70*1000))),"yyyy-MM-dd HH:mm:ss");
			// 设置还款子任务执行时间
			repaymentTaskVOs[i].setExecuteDateTime(executeDateTime);
		}
		Arrays.sort(repaymentTaskVOs);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "生成计划成功");
		map.put(CommonConstants.RESULT, repaymentTaskVOs);
		return map;
	}
	
	
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/create/temporary/percent/plan")
	public @ResponseBody Object generationTemporaryPlan2(HttpServletRequest request,
			@RequestParam(value = "userId") String suserId,
			@RequestParam(value = "creditCardNumber") String creditCardNumber,
			@RequestParam(value = "executeDate") String[] strExecuteDates, 
			@RequestParam(value = "amount") String amount,
			@RequestParam(value= "brandId")String brandId,
			@RequestParam(value = "count") String scount,
			@RequestParam(value = "version",required=false,defaultValue="1") String version
			) {
		int number = 10;
		amount = amount.trim();
		scount = scount.trim();
		suserId = suserId.trim();
		BigDecimal amountPercent = new BigDecimal(scount).setScale(2,BigDecimal.ROUND_DOWN);
		BigDecimal preAmount = amountPercent.multiply(new BigDecimal(amount));
		int count = new BigDecimal(amount).divide(preAmount,0,BigDecimal.ROUND_DOWN).intValue()+1;
		
		creditCardNumber = creditCardNumber.trim();
		
		int repaymentCountLimit = 0;
		int repaysumeSingleMoneyLimit = 0;
		int consumeSingleMoneyLimit = 0;
		int consumeCountLimit =0;
		String consumeChannelId = null;
		String repaymentChannelId = null;
		String consumeChannelTag = null;
		String repaymentChannelTag = null;
		
//		根据brandId查找配置信息
		CreditCardManagerConfig creditCardManagerConfig = creditCardManagerConfigBusiness.findByVersion(version);
		if(creditCardManagerConfig!=null){
			// 消费配置信息
			consumeSingleMoneyLimit = creditCardManagerConfig.getConSingleLimitMoney().intValue();
			consumeCountLimit = creditCardManagerConfig.getConSingleLimitCount();
			consumeChannelId = creditCardManagerConfig.getChannelId();
			consumeChannelTag = creditCardManagerConfig.getChannelTag();
			// 还款配置信息
			repaymentCountLimit = creditCardManagerConfig.getPaySingleLimitCount();
			repaysumeSingleMoneyLimit = creditCardManagerConfig.getPaySingleLimitMoney().intValue();
			repaymentChannelId = creditCardManagerConfig.getChannelId();
			repaymentChannelTag = creditCardManagerConfig.getChannelTag();
			int createOnOff = creditCardManagerConfig.getCreateOnOff();
			if (1 != createOnOff) {
				return ResultWrap.init(CommonConstants.FALIED, "该还款通道正在维护中,请使用其他还款通道!");
			}
		}else {
			return ResultWrap.init(CommonConstants.FALIED, "该还款通道正在维护中,请使用其他还款通道!");
		}
		
		Map<String, Object> map = new HashMap<>();
//		验证是否有批量生成的未执行计划
		boolean doesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO(suserId, creditCardNumber,version);
		boolean doesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO(suserId, creditCardNumber,version);
		if(doesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO || doesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您有未执行计划,请等待任务执行完后再生成计划!");
			return map;
		}
//		验证是否有首笔验证的已完成执行计划
//		null 没有 !null 有
		ConsumeTaskPOJO firstConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveOrderStatus1AndTaskType0ConsumeTaskPOJO(suserId, creditCardNumber,version);
//		null 没有 !null 有
		RepaymentTaskPOJO firstRepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveOrderStatus1AndTaskType0RepaymentTaskPOJO(suserId, creditCardNumber,version);
		if(firstConsumeTaskPOJO == null || firstRepaymentTaskPOJO == null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您未完成首笔验证,请等待计划执行完后再生成计划!");
			return map;
		}
//		验证日期格式是否正确
		Date[] executeDates = new Date[strExecuteDates.length];
		try {
			for(int i= 0;i < strExecuteDates.length;i++){
				executeDates[i] = DateUtil.getDateStringConvert(new Date(), strExecuteDates[i],"yyyy-MM-dd");
			}
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:选择日期格式有误,正确格式为:2000-01-01");
			return map;
		}
//		获取用户账单日和还款日
		CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(suserId, creditCardNumber,version);
		Integer billDate = creditCardAccount.getBillDate();
		Integer repaymentDate = creditCardAccount.getRepaymentDate();
		BigDecimal creditBlance = creditCardAccount.getCreditBlance();
		
		Date dateNow = DateUtil.getDateStringConvert(new Date(), DateUtil.getDateStringConvert(new String(),new Date() ,"yyyy-MM-dd"), "yyyy-MM-dd");
		dateNow = new Date(dateNow.getTime() + 24*60*60*1000);
		Integer executeDay = 0;
//		验证日期是否是今天以后
		for(int i = 0;i < executeDates.length;i++){
			if(dateNow.getTime() > executeDates[i].getTime() ){
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "只能选择今天以后的日期,请重新选择!");
				return map;
			}
//			如果有选择账单日和还款日,则验证任务执行日期是否在账单日之后还款日之前
			if(billDate!=0 && repaymentDate!=0){
				executeDay = Integer.valueOf(DateUtil.getDateStringConvert(new String(),executeDates[i] ,"dd"));
				if(billDate > repaymentDate){
					if(!((billDate <= executeDay)||(repaymentDate >= executeDay-2))){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "执行任务的日期只能为账单日之后至还款日前两天,请在该日期之间进行选择");
						return map;
					}
				}else{
					if(!((billDate <= executeDay)&&(repaymentDate >= executeDay-2))){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "执行任务的日期只能为账单日之后至还款日前两天,请在该日期之间进行选择");
						return map;
					}
				}
			}
		}
		
		// 还款笔数验证
		int count2;
		try {
			count2 = strExecuteDates.length*repaymentCountLimit;
		} catch (NumberFormatException e1) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "还款笔数输入不正确,请重新输入!");
			return map;
		}
		if(count > count2){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:选择的日期所对应的还款笔数应大于等于"+strExecuteDates.length + "笔而且小于等于" + strExecuteDates.length*repaymentCountLimit +"笔");
			return map;
		}
//		金额验证
		BigDecimal totalAmount;
		try {
			totalAmount = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_UP);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您输入的金额有误,请重新输入!");
			return map;
			
		}
//		总金额验证
//		BigDecimal perAveCountAmount = totalAmount.divide(new BigDecimal(scount),2,BigDecimal.ROUND_HALF_DOWN);
//		if (perAveCountAmount.compareTo(new BigDecimal(consumeSingleMoneyLimit * consumeCountLimit + number)) < 0) {
//			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
//			map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:当前金额可生成计划笔数为:" + (Integer.valueOf(amount.substring(0, amount.indexOf(".")==-1?amount.length():amount.indexOf(".")))/(consumeSingleMoneyLimit * consumeCountLimit + number))+ "笔");
//			return map;
//		}
//		信用卡验证
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("user", "error url request");
		String url = uri.toString() + "/v1.0/user/bank/verify/isuseable";
		LinkedMultiValueMap<String,String> requestEntity = new LinkedMultiValueMap<String,String>();
		requestEntity.add("userId", suserId);
		requestEntity.add("bankCardNumber", creditCardNumber);
		String resultString = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject resultJSONObject = JSONObject.fromObject(resultString);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase(resultJSONObject.getString(CommonConstants.RESP_CODE))){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, resultJSONObject.getString(CommonConstants.RESP_MESSAGE).isEmpty()?"生成计划失败,原因:该卡不可用,请更换一张信用卡!":resultJSONObject.getString(CommonConstants.RESP_MESSAGE));
			return map;
		}
		
		resultJSONObject = resultJSONObject.getJSONObject(CommonConstants.RESULT);
		String bankName = resultJSONObject.getString("bankName");
		
//		查询用户费率
		Map<String, Object> userChannelRate = getUserChannelRate(suserId,brandId.trim(),version);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase((String) userChannelRate.get(CommonConstants.RESP_CODE))){
			return userChannelRate;
		}
		
		resultJSONObject = (JSONObject) userChannelRate.get(CommonConstants.RESULT);
		String rateStr = resultJSONObject.getString("rate");
		String extraFeeStr = resultJSONObject.getString("extraFee");
		String withdrawFeeStr = resultJSONObject.getString("withdrawFee");
//		单笔还款手续费
		BigDecimal serviceCharge = new BigDecimal(extraFeeStr).add(new BigDecimal(withdrawFeeStr)).setScale(2, BigDecimal.ROUND_UP);;
//		费率
		BigDecimal rate = new BigDecimal(rateStr).setScale(4, BigDecimal.ROUND_UP);;
		
		preAmount = new BigDecimal(amount).divide(BigDecimal.valueOf(count),0,BigDecimal.ROUND_DOWN);
		
		
		int max = 0;
		if(CardConstss.CARD_VERSION_1.equals(version)) {
			if(count < 5) {
				max = 100;
			}else if(count > 5 && count < 10) {
				max = 40;
			}else if(count > 10 && count < 20) {
				max = 20;
			}else {
				max = 6;
			}
		}else{
			if(count < 5) {
				max = 12;
			}else if(count > 5 && count < 10) {
				max = 10;
			}else if(count > 10 && count < 20) {
				max = 8;
			}else {
				max = 6;
			}
		}
		
		
		int min = max/2;
		if(BigDecimal.valueOf(repaysumeSingleMoneyLimit).compareTo(preAmount) > 0) {
			throw new RuntimeException("单笔金额不足"+repaysumeSingleMoneyLimit+"元");
		}else if(BigDecimal.valueOf(repaysumeSingleMoneyLimit).compareTo(preAmount) == 0){
			min = 0;
			max = 0;
		}else if(preAmount.subtract(BigDecimal.valueOf(repaysumeSingleMoneyLimit)).compareTo(BigDecimal.valueOf(max)) <= 0){
			min = preAmount.subtract(BigDecimal.valueOf(repaysumeSingleMoneyLimit)).divide(BigDecimal.valueOf(2),0,BigDecimal.ROUND_DOWN).intValue();
			max = preAmount.subtract(BigDecimal.valueOf(repaysumeSingleMoneyLimit)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
		}
		preAmount = preAmount.subtract(BigDecimal.valueOf(max));
//		System.out.println(preAmount);
//		System.out.println(count);
		
		BigDecimal[][] perCountAmount = new BigDecimal[count][2+1];
		
		BigDecimal surplusCountAmount = BigDecimal.valueOf(count).multiply(BigDecimal.valueOf(max));
		
		BigDecimal surplusSubCountAmount = BigDecimal.ZERO;

		// 随机每笔金额
		BigDecimal randomCountAmount = BigDecimal.ZERO; 
		// 随机每次消费金额
		BigDecimal randomSubCountAmount = BigDecimal.ZERO;
		totalAmount = BigDecimal.ZERO;

		for (int i = 0; i < count; i++) {
			int result = min + (int)(Math.random() * ((max - min)+1));
			if (i != count - 1) {
				if(surplusCountAmount.compareTo(BigDecimal.ZERO)>0){
					randomCountAmount = new BigDecimal(result);
					perCountAmount[i][0] = preAmount.add(randomCountAmount);
					surplusCountAmount = surplusCountAmount.subtract(randomCountAmount);
				}else {
					perCountAmount[i][0] = preAmount;
				}
			}else {
				perCountAmount[i][0] = preAmount.add(surplusCountAmount);
			}
//			System.out.println(perCountAmount[i][0]);
			totalAmount = totalAmount.add(perCountAmount[i][0]);
		}
//		System.out.println(totalAmount);
		if(new BigDecimal(amount).compareTo(totalAmount) > 0) {
			perCountAmount[0][0] = perCountAmount[0][0].add(new BigDecimal(amount).subtract(totalAmount));
		}
		
		totalAmount = BigDecimal.ZERO;
		for(int i = 0;i < count;i++) {
			surplusSubCountAmount = perCountAmount[i][0].multiply(BigDecimal.valueOf(0.1)).setScale(0, BigDecimal.ROUND_DOWN);
			BigDecimal preConsumeAmount = perCountAmount[i][0].subtract(surplusSubCountAmount).divide(BigDecimal.valueOf(2), 1,BigDecimal.ROUND_HALF_UP);
			// 分配每笔还款的消费任务金额
			for (int j = 0; j < consumeCountLimit; j++) {
				if(j != consumeCountLimit-1){
					if(surplusSubCountAmount.compareTo(BigDecimal.ZERO)>0){
						randomSubCountAmount = new BigDecimal(new Random().nextInt(surplusSubCountAmount.intValue()));
						surplusSubCountAmount = surplusSubCountAmount.subtract(randomSubCountAmount);
						perCountAmount[i][j+1] = preConsumeAmount.add(randomSubCountAmount);
					}else{
						perCountAmount[i][j+1] = preConsumeAmount;
					}
				}else{
					perCountAmount[i][j+1] = preConsumeAmount.add(surplusSubCountAmount);
				}
//				System.out.println(perCountAmount[i][j+1].divide(BigDecimal.valueOf(10)));
				totalAmount = totalAmount.add(perCountAmount[i][j+1]);
				
				
				if(CardConstss.CARD_VERSION_2.equals(version)){
					if(perCountAmount[i][j+1].compareTo(BigDecimal.valueOf(1000)) > 0){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,信用卡单笔消费不能超过1000元,请减少还款金额,或者减少预留金额百分比再重新生成计划!");
						return map;
					}
					if(bankName!= null && bankName.contains("交通")){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "抱歉,该银行卡不支持使用此功能,请更换银行卡!");
						return map;
					}else if(bankName!= null && (bankName.contains("光大") || bankName.contains("中国银行"))){
						if(BigDecimal.valueOf(400).compareTo(perCountAmount[i][0]) < 0){
							map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,信用卡单日消费不能超过400元,请减少还款金额,或者减少预留金额百分比再重新生成计划");
							return map;
						}
					}
				}else if (CardConstss.CARD_VERSION_4.equals(version)) {
					if(perCountAmount[i][j+1].compareTo(BigDecimal.valueOf(1000)) > 0){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,信用卡单笔消费不能超过1000元,请减少还款金额,或者减少预留金额百分比再重新生成计划!");
						return map;
					}
					
					if (bankName!= null && (bankName.contains("光大") || bankName.contains("中国银行"))) {
						if(BigDecimal.valueOf(500).compareTo(perCountAmount[i][0]) < 0){
							map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							map.put(CommonConstants.RESP_MESSAGE, "生成计划失败,原因:由于银行限制,信用卡单日消费不能超过500元,请减少还款金额,或者减少预留金额百分比再重新生成计划");
							return map;
						}
					}
				}
			}
		}
//		System.out.println(totalAmount);

		Date nowTime = new Date();
		// 初始化还款任务
		RepaymentTaskVO[] repaymentTaskVOs = new RepaymentTaskVO[count];
		for (int i = 0; i < count; i++) {
			repaymentTaskVOs[i] = new RepaymentTaskVO();
			
//			repaymentTaskVOs[i].setConsumeTaskVOs(new ConsumeTaskVO[consumeCountLimit]);
			// 设置userId
			repaymentTaskVOs[i].setUserId(suserId);
			// 设置还款卡号
			repaymentTaskVOs[i].setCreditCardNumber(creditCardNumber);
			// 设置还款通道id
			repaymentTaskVOs[i].setChannelId(repaymentChannelId);
			// 设置还款通道tag
			repaymentTaskVOs[i].setChannelTag(repaymentChannelTag);
			// 设置还款金额
			repaymentTaskVOs[i].setAmount(perCountAmount[i][0]);
			// 设置还款手续费
			repaymentTaskVOs[i].setServiceCharge(serviceCharge);
			// 设置消费费率
			repaymentTaskVOs[i].setRate(rate);
			// 设置总手续费
			BigDecimal totalServiceCharge = repaymentTaskVOs[i].getAmount().add(serviceCharge).setScale(2, BigDecimal.ROUND_UP).divide( BigDecimal.ONE.subtract(rate),2,BigDecimal.ROUND_UP).subtract(repaymentTaskVOs[i].getAmount());
			totalServiceCharge = totalServiceCharge.add(BigDecimal.valueOf(0.01));
			repaymentTaskVOs[i].setTotalServiceCharge(totalServiceCharge);
			// 设置任务描述
			repaymentTaskVOs[i].setDescription("还款计划");
			// 设置创建时间
			repaymentTaskVOs[i].setCreateTime(DateUtil.getDateStringConvert(new String(), nowTime, "yyyy-MM-dd HH:mm:ss"));
		}
		
		//随机分配执行日期
		Date[] executeTime = new Date[count];
		
		for(int i=0;i < (strExecuteDates.length>count?count:strExecuteDates.length);i++){
//			executeTime[i] = DateUtil.getDateFromStr(strExecuteDates[i]); 
			executeTime[i] = DateUtil.getDateStringConvert(new Date(), strExecuteDates[i], "yyyy-MM-dd");
			repaymentTaskVOs[i].setExecuteDate(strExecuteDates[i]);
		}
//		还款笔数和日期的差值,差值笔数将随机分配至各天
		int differencCount = count - strExecuteDates.length;
		int index = 0;
		if (differencCount > 0 && differencCount == strExecuteDates.length) {
			int j = 0;
			for (int i = strExecuteDates.length; i < count; i++){
				repaymentTaskVOs[i].setExecuteDate(strExecuteDates[j]);
				j++;
			}
		}else if(differencCount > 0){
			for (int i = strExecuteDates.length; i < count; i++) {
				index =new Random().nextInt(strExecuteDates.length);
				if (strExecuteDates[index] != null) {
					repaymentTaskVOs[i].setExecuteDate(strExecuteDates[index]);
					strExecuteDates[index] = null;
				} else {
					for (int j = 0; j < strExecuteDates.length; j++) {
						if (strExecuteDates[j] != null) {
							repaymentTaskVOs[i].setExecuteDate(strExecuteDates[j]);
							strExecuteDates[j] = null;
							break;
						}
					}
				}
			}
		}
		
		Random random = new Random();
		// 随机分配执行时间
		String initTime = null;
		String executeDateTime = null;
		Date initDateTime = null;
		int randomInt = 0;
		for(int i=0;i < count;i++){
			if(i >= strExecuteDates.length){
				if(CardConstss.CARD_VERSION_1.equals(version) || CardConstss.CARD_VERSION_6.equals(version)) {
					initTime = " 16:00:00";
				}else if(CardConstss.CARD_VERSION_2.equals(version)) {
					initTime = " 14:30:00";
				}else if(CardConstss.CARD_VERSION_3.equals(version) || CardConstss.CARD_VERSION_5.equals(version)) {
					initTime = " 15:00:00";
				}else if(CardConstss.CARD_VERSION_4.equals(version)) {
					initTime = " 15:30:00";
				}
			}else{
				initTime = " 09:00:00";
			}
			
			// 设置还款任务id
			repaymentTaskVOs[i].setRepaymentTaskId(repaymentTaskVOs[i].getExecuteDate().replace("-", "")+DateUtil.getDateStringConvert(new String(), new Date(),"HHSSS")+ random.nextInt(9)+ random.nextInt(9)+random.nextInt(9)+i+"1");
			// 设置消费子任务字段
			
//			String[] consumeTypeName = {"娱乐","购物","其他","通信","交通","住宿","餐饮"};
			List<String> consumeTypeName = new ArrayList<>();
			consumeTypeName.add("娱乐");
			consumeTypeName.add("购物");
			consumeTypeName.add("其他");
			consumeTypeName.add("通信");
			consumeTypeName.add("交通");
			consumeTypeName.add("住宿");
			consumeTypeName.add("餐饮");
			for (int j = 0; j < consumeCountLimit; j++) {
//				repaymentTaskVOs[i].getConsumeTaskVOs()[j] = new ConsumeTaskVO();
				repaymentTaskVOs[i].getConsumeTaskVOs().add(new ConsumeTaskVO());
//				ConsumeTaskVO consumeTaskVO = repaymentTaskVOs[i].getConsumeTaskVOs()[j];
				ConsumeTaskVO consumeTaskVO = repaymentTaskVOs[i].getConsumeTaskVOs().get(j);
				// 设置userId
				consumeTaskVO.setUserId(suserId);
				// 设置消费通道id
				consumeTaskVO.setChannelId(consumeChannelId);
				// 设置消费通道tag
				consumeTaskVO.setChannelTag(consumeChannelTag);
				// 设置还款任务id
				consumeTaskVO.setRepaymentTaskId(repaymentTaskVOs[i].getRepaymentTaskId());
				// 设置消费卡号
				consumeTaskVO.setCreditCardNumber(creditCardNumber);
				// 设置消费任务
				consumeTaskVO.setDescription("消费计划");
				// 设置消费类型
				randomInt = new Random().nextInt(consumeTypeName.size());
				consumeTaskVO.setConsumeType(consumeTypeName.get(randomInt));
				consumeTypeName.remove(randomInt);
				
				// 设置消费金额
				consumeTaskVO.setAmount(perCountAmount[i][j + 1]);
				if(j == 0){
					consumeTaskVO.setRealAmount(consumeTaskVO.getAmount().add(repaymentTaskVOs[i].getTotalServiceCharge()));
					consumeTaskVO.setServiceCharge(repaymentTaskVOs[i].getTotalServiceCharge());
				}else{
					consumeTaskVO.setRealAmount(consumeTaskVO.getAmount());
				}
				// 设置执行日期
				consumeTaskVO.setExecuteDate(repaymentTaskVOs[i].getExecuteDate());
				// 设置创建时间
				consumeTaskVO.setCreateTime(repaymentTaskVOs[i].getCreateTime());
				// 设置消费子任务id
				consumeTaskVO.setConsumeTaskId(Long.valueOf(repaymentTaskVOs[i].getRepaymentTaskId())+(j+1)+"");
				
				initDateTime = DateUtil.getDateStringConvert(new Date(), consumeTaskVO.getExecuteDate() + initTime, "yyyy-MM-dd HH:mm:ss");
				executeDateTime = DateUtil.getDateStringConvert(new String(),new Date(initDateTime.getTime()+(30*70*1000)+(random.nextInt(60*70*1000))),"yyyy-MM-dd HH:mm:ss");
				// 设置消费子任务执行日期时间
				consumeTaskVO.setExecuteDateTime(executeDateTime);
				initTime = executeDateTime.substring(executeDateTime.indexOf(" "));
			}
			initDateTime = DateUtil.getDateStringConvert(new Date(), repaymentTaskVOs[i].getExecuteDate() + initTime, "yyyy-MM-dd HH:mm:ss");
			executeDateTime = DateUtil.getDateStringConvert(new String(),new Date(initDateTime.getTime()+(30*70*1000)+(random.nextInt(60*70*1000))),"yyyy-MM-dd HH:mm:ss");
			// 设置还款子任务执行时间
			repaymentTaskVOs[i].setExecuteDateTime(executeDateTime);
		}
		Arrays.sort(repaymentTaskVOs);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "生成计划成功");
		map.put(CommonConstants.RESULT, repaymentTaskVOs);
		return map;
	}
	
	
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/save/all/plan")
	public @ResponseBody Object saveRepaymentTaskAndConsumeTask(HttpServletRequest request,
			@RequestParam(value="taskJSON")String taskJSON,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object>map = new HashMap<>();
		
		Map<String, Object> verifyStringFiledIsNullMap = creditCardManagerAuthorizationHandle.verifyStringFiledIsNull(taskJSON);
		if(!CommonConstants.SUCCESS.equals(verifyStringFiledIsNullMap.get(CommonConstants.RESP_CODE))){
			return verifyStringFiledIsNullMap;
		}
		taskJSON = taskJSON.trim();
		try {
			taskJSON = URLDecoder.decode(taskJSON,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "参数URL解码失败");
			return map;
			
		}
		
		
//		将任务解析成JSONArray
		JSONArray allTaskJSONArray;
		try {
			allTaskJSONArray = JSONArray.fromObject(taskJSON);
		} catch (Exception e) {
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "保存计划失败,原因:taskJSON参数异常!");
			return map;
		}
		JSONObject repaymentTaskJSONObject = null;
//		还款任务PO数组
		RepaymentTaskPOJO[] repaymentTaskPOJOs = new RepaymentTaskPOJO[allTaskJSONArray.size()];
//		消费任务PO数组
		List<ConsumeTaskPOJO> consumeTaskPOJOs = new ArrayList<>();
//		ConsumeTaskVO[] consumeTaskVOs = new ConsumeTaskVO[consumeCountLimit];
		List<ConsumeTaskVO> consumeTaskVOs = null;
		Map<String,Class> classMap = new HashMap<>();
		classMap.put("consumeTaskVOs", ConsumeTaskVO.class);
		ConsumeTaskVO consumeTaskVO = null;
		ConsumeTaskPOJO consumeTaskPOJO = null;
//		将解析出的JONSArray注入还款任务PO数组和消费任务PO数组中
		for(int i=0;i < allTaskJSONArray.size();i++){
			repaymentTaskJSONObject = allTaskJSONArray.getJSONObject(i);
			repaymentTaskPOJOs[i] = (RepaymentTaskPOJO) JSONObject.toBean(repaymentTaskJSONObject, RepaymentTaskPOJO.class,classMap);
			repaymentTaskPOJOs[i].setVersion(version);
			consumeTaskVOs = repaymentTaskPOJOs[i].getConsumeTaskVOs();
			for(int j = 0;j < consumeTaskVOs.size();j++){
				consumeTaskPOJO = new ConsumeTaskPOJO();
				consumeTaskVO = consumeTaskVOs.get(j);
				BeanUtils.copyProperties(consumeTaskVO, consumeTaskPOJO);
				if(CardConstss.CARD_VERSION_1.equals(version)){
					if(consumeTaskPOJO.getRealAmount().compareTo(BigDecimal.valueOf(5000)) > 0){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "保存计划失败,原因:由于银行限制,单笔消费不能超过5000元,请减少还款金额,或者增加还款天数再重新生成计划!");
						return map;
					}
				}else if(CardConstss.CARD_VERSION_2.equals(version)){
					if(consumeTaskPOJO.getRealAmount().compareTo(BigDecimal.valueOf(1000)) > 0){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "保存计划失败,原因:由于银行限制,单笔消费不能超过1000元,请减少还款金额,或者减少预留金额百分比再重新生成计划!");
						return map;
					}
				}

				consumeTaskPOJO.setDescription(consumeTaskPOJO.getDescription()+"|"+consumeTaskVO.getConsumeType());
				consumeTaskPOJO.setVersion(version);
				consumeTaskPOJOs.add(consumeTaskPOJO);
			}
		}
		
		boolean doesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO(repaymentTaskPOJOs[0].getUserId(), repaymentTaskPOJOs[0].getCreditCardNumber(),version);
		boolean doesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO(repaymentTaskPOJOs[0].getUserId(), repaymentTaskPOJOs[0].getCreditCardNumber(),version);
		if(doesHaveTaskStatus0AndTaskType2ConsumeTaskPOJO || doesHaveTaskStatus0AndTaskType2RepaymentTaskPOJO){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您有未执行计划,请等待任务执行完后再生成计划!");
			return map;
		}
		
		LinkedMultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", repaymentTaskPOJOs[0].getUserId());
		requestEntity.add("cardNo", repaymentTaskPOJOs[0].getCreditCardNumber());
		Map<String, Object> restTemplateDoPost = util.restTemplateDoPost("user", "/v1.0/user/bank/find/bankphone", requestEntity);
		if(CommonConstants.SUCCESS.equals(restTemplateDoPost.get(CommonConstants.RESP_CODE))){
			JSONObject resulJSON = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
			String bankName = resulJSON.getString("bankName");
			
			if(CardConstss.CARD_VERSION_1.equals(version)){
				if(bankName!= null && bankName.contains("光大")){
					for(ConsumeTaskPOJO model:consumeTaskPOJOs){
						if(BigDecimal.valueOf(2000).compareTo(model.getRealAmount()) < 0){
							map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							map.put(CommonConstants.RESP_MESSAGE, "保存计划失败,原因:由于银行限制,光大银行信用卡单笔消费不能超过2000元,请减少还款金额,或者增加还款天数再重新生成计划");
							return map;
						}
					}
				}
			}else if(CardConstss.CARD_VERSION_2.equals(version)){
				if(bankName!= null && (bankName.contains("光大"))){
					for(RepaymentTaskPOJO model:repaymentTaskPOJOs){
						if(BigDecimal.valueOf(400).compareTo(model.getRealAmount()) < 0){
							map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							map.put(CommonConstants.RESP_MESSAGE, "保存计划失败,原因:由于银行限制,信用卡单日消费不能超过400元,请减少还款金额,或者减少预留金额百分比再重新生成计划");
							return map;
						}
					}
				}
			}
			Map<String, Object> verifyDoesSupportBank = creditCardManagerAuthorizationHandle.verifyDoesSupportBank(version, bankName);
			if (!CommonConstants.SUCCESS.equals(verifyDoesSupportBank.get(CommonConstants.RESP_CODE))) {
				return verifyDoesSupportBank;
			}
		}
		
		
		try {
			// 对还款任务PO进行持久化
//				repaymentTaskPOJOs = repaymentTaskPOJOBusiness.saveArray(repaymentTaskPOJOs);
			// 对消费任务PO进行持久化
//				consumeTaskPOJOs = consumeTaskPOJOBusiness.saveArrayList(consumeTaskPOJOs);
				consumeTaskPOJOBusiness.saveArrayListTaskAll(consumeTaskPOJOs,repaymentTaskPOJOs);
		} catch (Exception e) {
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "保存计划失败,原因:服务器正忙,请重新生成计划后重试!");
			return map;
		}
		
//		map.put("repaymentTask", repaymentTaskPOJOs);
//		map.put("consumeTask", consumeTaskPOJOs);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "保存计划成功!");
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/verify/card/isuserable")
	public @ResponseBody Object verifyCardIsUseable(HttpServletRequest request,
			@RequestParam(value="userId")String userId,
			@RequestParam(value="creditCardNumber")String creditCardNumber,
			@RequestParam(value="brandId")String brandId,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		userId = userId.trim();
		creditCardNumber = creditCardNumber.trim();
		Map<String,Object>map = new HashMap<>();
		if("".equals(userId)||"".equals(creditCardNumber) || "".equals(version)){
			map.put(CommonConstants.RESP_CODE, CardConstss.FAIL_CODE);
			map.put(CommonConstants.RESP_MESSAGE, "验证失败,传入参数不能为空!");
			return map;
		}
		
		JSONObject resultJSONObject = creditCardManagerAuthorizationHandle.verifyCreditCard(userId, creditCardNumber);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase(resultJSONObject.getString(CommonConstants.RESP_CODE))){
			map.put(CommonConstants.RESP_CODE, CardConstss.FAIL_CODE);
			map.put(CommonConstants.RESP_MESSAGE, resultJSONObject.getString(CommonConstants.RESP_MESSAGE).isEmpty()?"验证失败,原因:该卡不可用,请更换一张信用卡!":resultJSONObject.getString(CommonConstants.RESP_MESSAGE));
			return map;
		}
		JSONObject resultBankCardJSONObject = resultJSONObject.getJSONObject(CommonConstants.RESULT);
		String securityCode = resultBankCardJSONObject.getString("securityCode");
		if(securityCode != null && (securityCode.length() !=3 || !securityCode.matches("^[0-9]*$"))){
			map.put(CommonConstants.RESP_CODE, CardConstss.FAIL_CODE);
			map.put(CommonConstants.RESP_MESSAGE, "安全码非法,请点击【修改信息】重新设置");
			return map;
		}
		
		CreditCardAccount model = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userId,creditCardNumber,version);

		
		Map<String, Object> verifyCreditCardDoesHaveSecurityCodeAndExpiredTime = creditCardManagerAuthorizationHandle.verifyCreditCardDoesHaveSecurityCodeAndExpiredTime(userId, creditCardNumber);
		if(!CommonConstants.SUCCESS.equals(verifyCreditCardDoesHaveSecurityCodeAndExpiredTime.get(CommonConstants.RESP_CODE))){
			verifyCreditCardDoesHaveSecurityCodeAndExpiredTime.put(CommonConstants.RESP_CODE, CardConstss.FAIL_CODE);
			return verifyCreditCardDoesHaveSecurityCodeAndExpiredTime;
		}
		
		String bankName = resultBankCardJSONObject.getString("bankName");
		Map<String, Object> verifyDoesSupportBank = creditCardManagerAuthorizationHandle.verifyDoesSupportBank(version, bankName);
		if (!CommonConstants.SUCCESS.equals(verifyDoesSupportBank.get(CommonConstants.RESP_CODE))) {
			return verifyDoesSupportBank;
		}
		/*if(CardConstss.CARD_VERSION_2.equals(version) && model==null && bankName != null){
			if(bankName.contains("交通") || bankName.contains("农业")){
				return ResultWrap.init(CardConstss.NONSUPPORT, "抱歉,该银行卡暂不支持使用此功能");
			}
		}else if(CardConstss.CARD_VERSION_1.equals(version) && model==null && bankName!= null){
			if (bankName.contains("农业") || bankName.contains("招商") || bankName.contains("交通")) {
				return ResultWrap.init(CardConstss.NONSUPPORT, "抱歉,该银行卡暂不支持使用此功能");
			}
		}else if (CardConstss.CARD_VERSION_4.equals(version) && model==null && bankName!= null) {
			if(bankName.contains("建设")){
				return ResultWrap.init(CardConstss.NONSUPPORT, "抱歉,该银行卡暂不支持使用此功能");
			}
		}else if (CardConstss.CARD_VERSION_3.equals(version) && model==null && bankName!= null) {
			if(bankName.contains("浦发")){
				return ResultWrap.init(CardConstss.NONSUPPORT, "抱歉,该银行卡暂不支持使用此功能");
			}
		}*/
		
//		resultJSONObject = (JSONObject) verifyCreditCardDoesHaveSecurityCodeAndExpiredTime.get(CommonConstants.RESULT);
		
//		查询用户费率
		Map<String, Object> userChannelRate = getUserChannelRate(userId,brandId.trim(),version);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase((String) userChannelRate.get(CommonConstants.RESP_CODE))){
			userChannelRate.put(CommonConstants.RESP_CODE, CardConstss.FAIL_CODE);
			return userChannelRate;
		}
		int firstMoney = 0;
		CreditCardManagerConfig creditCardManagerConfig = creditCardManagerConfigBusiness.findByVersion(version);
		if(creditCardManagerConfig != null){
			firstMoney = creditCardManagerConfig.getFirstMoney();
		}else {
			return ResultWrap.init(CardConstss.NONSUPPORT, "该还款通道正在维护中,请使用其他还款通道!");
		}
		int createOnOff = creditCardManagerConfig.getCreateOnOff();
		if (model == null && 1 != createOnOff) {
			return ResultWrap.init(CardConstss.NONSUPPORT, "该还款通道正在维护中,请使用其他还款通道!");
		}
		
		resultJSONObject = (JSONObject) userChannelRate.get(CommonConstants.RESULT);
		String rateStr = resultJSONObject.getString("rate");
		String extraFeeStr = resultJSONObject.getString("extraFee");
		String withdrawFeeStr = resultJSONObject.getString("withdrawFee");
		BigDecimal serviceCharge = new BigDecimal(extraFeeStr).add(new BigDecimal(withdrawFeeStr)).setScale(2, BigDecimal.ROUND_UP);;
		BigDecimal rate = new BigDecimal(rateStr).setScale(4, BigDecimal.ROUND_UP);
		BigDecimal totalserviceCharge = BigDecimal.ZERO;
		if(CardConstss.CARD_VERSION_1.equals(version)) {
			totalserviceCharge = serviceCharge.add(BigDecimal.valueOf(firstMoney)).add(BigDecimal.valueOf(2)).divide(BigDecimal.ONE.subtract(rate),2,BigDecimal.ROUND_UP).subtract(BigDecimal.valueOf(firstMoney));
		}else{
			totalserviceCharge = serviceCharge.add(BigDecimal.valueOf(firstMoney)).divide(BigDecimal.ONE.subtract(rate),2,BigDecimal.ROUND_UP).subtract(BigDecimal.valueOf(firstMoney));
		}
		BigDecimal amount = BigDecimal.valueOf(firstMoney).add(totalserviceCharge).setScale(2, BigDecimal.ROUND_UP);
		/*if(CardConstss.CARD_VERSION_2.equals(version)) {
			Map<String, Object> verifyVersion2DoesHaveBandCard = creditCardManagerAuthorizationHandle.verifyVersion2DoesHaveBandCard(creditCardNumber,rate.toString(),serviceCharge.toString());
			if(!CommonConstants.SUCCESS.equals(verifyVersion2DoesHaveBandCard.get(CommonConstants.RESP_CODE))) {
				if(!CardConstss.TO_BAND_CARD.equals(verifyVersion2DoesHaveBandCard.get(CommonConstants.RESP_CODE))){
					return ResultWrap.init(CardConstss.NONSUPPORT,(String)verifyVersion2DoesHaveBandCard.get(CommonConstants.RESP_MESSAGE));
				}
				return verifyVersion2DoesHaveBandCard;
			}
		}else if (CardConstss.CARD_VERSION_3.equals(version)) {
			Map<String, Object> verifyVersion3DoesHaveBandCard = creditCardManagerAuthorizationHandle.verifyVersion3DoesHaveBandCard(creditCardNumber,rate.toString(),serviceCharge.toString(),userId);
			if (!CommonConstants.SUCCESS.equals(verifyVersion3DoesHaveBandCard.get(CommonConstants.RESP_CODE))) {
				return ResultWrap.init(CardConstss.FAIL_CODE,(String)verifyVersion3DoesHaveBandCard.get(CommonConstants.RESP_MESSAGE));
			}
		}else if (CardConstss.CARD_VERSION_4.equals(version)) {
			Map<String, Object> verifyVersion4DoesHaveBandCard = creditCardManagerAuthorizationHandle.verifyVersion4DoesHaveBandCard(creditCardNumber);
			if (!CommonConstants.SUCCESS.equals(verifyVersion4DoesHaveBandCard.get(CommonConstants.RESP_CODE))) {
				if(!CardConstss.TO_BAND_CARD.equals(verifyVersion4DoesHaveBandCard.get(CommonConstants.RESP_CODE))){
					return ResultWrap.init(CardConstss.NONSUPPORT,(String)verifyVersion4DoesHaveBandCard.get(CommonConstants.RESP_MESSAGE));
				}
				return verifyVersion4DoesHaveBandCard;
			}
		}*/
		
		Map<String, Object> verifyDoesHaveBandCard = creditCardManagerAuthorizationHandle.verifyDoesHaveBandCard(userId, creditCardNumber, rateStr, serviceCharge.toString(), version,resultBankCardJSONObject);
		if(!CommonConstants.SUCCESS.equals(verifyDoesHaveBandCard.get(CommonConstants.RESP_CODE))) {
			if(!CardConstss.TO_BAND_CARD.equals(verifyDoesHaveBandCard.get(CommonConstants.RESP_CODE))){
				return ResultWrap.init(CardConstss.NONSUPPORT,(String)verifyDoesHaveBandCard.get(CommonConstants.RESP_MESSAGE));
			}
			return verifyDoesHaveBandCard;
		}
		
		RepaymentTaskPOJO firstRepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType0RepaymentTaskPOJO(userId, creditCardNumber,version);
		if(firstRepaymentTaskPOJO != null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "未对首笔消费进行还款,点击确定进行继续还款");
			return map;
		}
		boolean verifyDoesHaveTaskStatus1AndTaskType0AndOrderStatus4RepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus1AndTaskType0AndOrderStatus4RepaymentTaskPOJO(userId,creditCardNumber,version);
		if(verifyDoesHaveTaskStatus1AndTaskType0AndOrderStatus4RepaymentTaskPOJO){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "点击确定继续进行还款");
			return map;
		}
		
		if(model==null){
			map.put(CommonConstants.RESP_MESSAGE,"该卡首次使用,需要进行金额为"+amount+"元的首笔消费验证,扣除"+totalserviceCharge+"元手续费后,将还入"+firstMoney+"元到该卡中!");
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
		}else{
			map.put(CommonConstants.RESP_MESSAGE, "验证成功,可进入生成还款计划!");
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		}
		map.put(CommonConstants.RESULT, model);
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/first/use/credit/card/manager")
	public @ResponseBody Object registCreditCardManager(HttpServletRequest request,
			@RequestParam(value="userId")String userIdStr,
			@RequestParam(value="creditCardNumber")String creditCardNumber,
			@RequestParam(value="phone")String phone,
			@RequestParam(value="brandId")String brandId,
			@RequestParam(value="creditBlance",required=false,defaultValue="0")String creditBlance,
			@RequestParam(value="billDate",required=false,defaultValue="0")String billDate,
			@RequestParam(value="repaymentDate",required=false,defaultValue="0")String repaymentDate,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object>map = new HashMap<>();
		
		int firstMoney = 0;
		String consumeChannelId = null;
		String repaymentChannelId = null;
		String consumeChannelTag = null;
		String repaymentChannelTag = null;
		
		CreditCardManagerConfig creditCardManagerConfig = creditCardManagerConfigBusiness.findByVersion(version);
		if(creditCardManagerConfig!=null){
			consumeChannelId = creditCardManagerConfig.getChannelId();
			consumeChannelTag = creditCardManagerConfig.getChannelTag();
			firstMoney = creditCardManagerConfig.getFirstMoney();
			repaymentChannelId = creditCardManagerConfig.getChannelId();
			repaymentChannelTag = creditCardManagerConfig.getChannelTag();
			int createOnOff = creditCardManagerConfig.getCreateOnOff();
			if (1 != createOnOff) {
				return ResultWrap.init(CommonConstants.FALIED, "该还款通道正在维护中,请使用其他还款通道!");
			}
		}else {
			return ResultWrap.init(CommonConstants.FALIED, "该还款通道正在维护中,请使用其他还款通道!");
		}
		
//		判断通道开放时间
		Map<String, Object> verifyOpenTime = creditCardManagerAuthorizationHandle.verifyOpenTime(version);
		if(!CommonConstants.SUCCESS.equals(verifyOpenTime.get(CommonConstants.RESP_CODE))){
			return verifyOpenTime;
		}
		
//		限制用户同一时间多次请求
		Map<String, Object> restClientLimit = creditCardManagerAuthorizationHandle.restClientLimit("firstUseCreditCardManager", 10, userIdStr,creditCardNumber);
		if(!CommonConstants.SUCCESS.equals(restClientLimit.get(CommonConstants.RESP_CODE))){
			return restClientLimit;
		}
		
//		获取用户的卡信息
		LinkedMultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", userIdStr);
		requestEntity.add("cardNo", creditCardNumber);
		String resultString = restTemplate.postForObject( "http://user/v1.0/user/bank/find/bankphone", requestEntity,String.class);
		JSONObject resultJSON = JSONObject.fromObject(resultString);
		resultJSON = resultJSON.getJSONObject(CommonConstants.RESULT);
		String bankName = resultJSON.getString("bankName");
		/*if(CardConstss.CARD_VERSION_1.equals(version) && bankName!= null &&(bankName.contains("招商") || bankName.contains("农业"))){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "抱歉,该银行卡不支持使用此功能,请更换银行卡!");
			return map;
		}*/
		Map<String, Object> verifyDoesSupportBank = creditCardManagerAuthorizationHandle.verifyDoesSupportBank(version, bankName);
		if (!CommonConstants.SUCCESS.equals(verifyDoesSupportBank.get(CommonConstants.RESP_CODE))) {
			return verifyDoesSupportBank;
		}
		
		userIdStr = userIdStr.trim();
		creditCardNumber = creditCardNumber.trim();
		JSONObject resultJSONObject = null;
//		验证是否为可用信用卡
		resultJSONObject = creditCardManagerAuthorizationHandle.verifyCreditCard(userIdStr, creditCardNumber);
		if(!CommonConstants.SUCCESS.equalsIgnoreCase(resultJSONObject.getString(CommonConstants.RESP_CODE))){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, resultJSONObject.getString(CommonConstants.RESP_MESSAGE).isEmpty()?"首次功能验证失败,原因:该卡不可用,请更换一张信用卡!":resultJSONObject.getString(CommonConstants.RESP_MESSAGE));
			return map;
		}
		
//		验证该卡是否在其他号码使用
		Map<String, Object> creditCardNumberIsUse = creditCardManagerAuthorizationHandle.verifyCreditCardNumberIsUse(creditCardNumber,userIdStr,version);
		if(!CommonConstants.SUCCESS.equals(creditCardNumberIsUse.get(CommonConstants.RESP_CODE))){
			return creditCardNumberIsUse;
		}
		
//		判断是否有注册,而且已完成首笔还款则无需进行首笔验证
		Map<String, Object> creditCardAccountMap = creditCardManagerAuthorizationHandle.verifyIsRegister(userIdStr, creditCardNumber,version);
		
//		判断是否完成首笔还款
		Map<String, Object> verifyIsCompletedFirstRepaymentTask = creditCardManagerAuthorizationHandle.verifyIsCompletedFirstRepaymentTask(userIdStr, creditCardNumber,version);
		RepaymentTaskPOJO firstRepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveOrderStatus1AndTaskType0RepaymentTaskPOJO(userIdStr, creditCardNumber,version);
		if(firstRepaymentTaskPOJO != null){
			if(!CommonConstants.SUCCESS.equals(creditCardAccountMap.get(CommonConstants.RESP_CODE))){
				Date nowTime = new Date();
				CreditCardAccount creditCardAccount = new CreditCardAccount();
				creditCardAccount.setUserId(userIdStr);
				creditCardAccount.setCreditCardNumber(creditCardNumber);
				creditCardAccount.setPhone(phone);
				creditCardAccount.setBillDate(Integer.valueOf(billDate));
				creditCardAccount.setRepaymentDate(Integer.valueOf(repaymentDate));
				creditCardAccount.setCreditBlance(new BigDecimal(creditBlance));
				creditCardAccount.setLastUpdateTime(nowTime);
				creditCardAccount = creditCardAccountBusiness.save(creditCardAccount);
			}
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "首笔任务完成,可进入生成计划!");
			return map;
		}
		
//		判断是否已经注册和是否完成首笔还款
		if(CommonConstants.SUCCESS.equals(creditCardAccountMap.get(CommonConstants.RESP_CODE))&&CommonConstants.SUCCESS.equals(verifyIsCompletedFirstRepaymentTask.get(CommonConstants.RESP_CODE))){
			return creditCardAccountMap;
		}
		
//		判断是否有待完成的首笔还款任务
		RepaymentTaskPOJO waitNotifyRepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus1AndOrderStatus4RepaymentTaskPOJO(userIdStr, creditCardNumber,version);
		
//		判断是否有待完成的首笔消费任务
		ConsumeTaskPOJO waitNotifyConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus1AndOrderStatus4ConsumeTaskPOJO(userIdStr, creditCardNumber, version);
		if(waitNotifyConsumeTaskPOJO != null){
			JSONObject orderStatus = null;
			orderStatus = baseExecutor.getOrderStatusByVersion(waitNotifyConsumeTaskPOJO.getOrderCode(), CommonConstants.ORDER_TYPE_CONSUME, waitNotifyConsumeTaskPOJO.getVersion());
			LOG.info("任务查询结果=====" + orderStatus + "=====" + waitNotifyConsumeTaskPOJO);
			if (CardConstss.WAIT_NOTIFY.equals(orderStatus.getString(CommonConstants.RESP_CODE))) {
				return ResultWrap.init(CommonConstants.FALIED, "等待首笔消费成功,请稍后!");
			}else if (CommonConstants.FALIED.equals(orderStatus.getString(CommonConstants.RESP_CODE))) {
				waitNotifyConsumeTaskPOJO.setTaskStatus(0);
				waitNotifyConsumeTaskPOJO.setOrderStatus(0);
				consumeTaskPOJOBusiness.save(waitNotifyConsumeTaskPOJO);
				return ResultWrap.init(CommonConstants.FALIED, "首笔消费失败,请再次点击进行首笔消费");
			}else if (CommonConstants.SUCCESS.equals(orderStatus.getString(CommonConstants.RESP_CODE))) {
				this.updateTaskStatusByOrderCode(request, waitNotifyConsumeTaskPOJO.getOrderCode(), waitNotifyConsumeTaskPOJO.getVersion());
				baseExecutor.updatePaymentOrderByOrderCode(waitNotifyConsumeTaskPOJO.getOrderCode());
				return ResultWrap.init(CommonConstants.FALIED, "首笔消费成功,请再次点击进行首笔还款!");
			}
		}
		
		if(waitNotifyRepaymentTaskPOJO != null){
			JSONObject orderStatus = null;
			orderStatus = baseExecutor.getOrderStatusByVersion(waitNotifyRepaymentTaskPOJO.getOrderCode(), CommonConstants.ORDER_TYPE_REPAYMENT, waitNotifyRepaymentTaskPOJO.getVersion());
			LOG.info("任务查询结果=====" + orderStatus + "=====" + waitNotifyRepaymentTaskPOJO);
			if (CardConstss.WAIT_NOTIFY.equals(orderStatus.getString(CommonConstants.RESP_CODE))) {
				return ResultWrap.init(CommonConstants.FALIED, "等待首笔还款成功,请稍后!");
			}else if (CommonConstants.FALIED.equals(orderStatus.getString(CommonConstants.RESP_CODE))) {
				waitNotifyRepaymentTaskPOJO.setTaskStatus(0);
				waitNotifyRepaymentTaskPOJO.setOrderStatus(0);
				repaymentTaskPOJOBusiness.save(waitNotifyRepaymentTaskPOJO);
				creditCardAccountBusiness.updateCreditCardAccountAndVersion(waitNotifyRepaymentTaskPOJO.getUserId(), waitNotifyRepaymentTaskPOJO.getCreditCardNumber(), waitNotifyRepaymentTaskPOJO.getRepaymentTaskId(), 3, waitNotifyRepaymentTaskPOJO.getRealAmount(), "首笔还款失败,解除冻结金额", waitNotifyRepaymentTaskPOJO.getVersion());
				return ResultWrap.init(CommonConstants.FALIED, "首笔还款失败,请再次点击进行首笔还款");
			}else if (CommonConstants.SUCCESS.equals(orderStatus.getString(CommonConstants.RESP_CODE))) {
				this.updateTaskStatusByOrderCode(request, waitNotifyRepaymentTaskPOJO.getOrderCode(), waitNotifyRepaymentTaskPOJO.getVersion());
				baseExecutor.updatePaymentOrderByOrderCode(waitNotifyRepaymentTaskPOJO.getOrderCode());
				return ResultWrap.init(CommonConstants.SUCCESS, "首笔任务完成,可进入生成计划!");
			}
		}
		
		
//		判断是否有已完成的消费任务
/*		Map<String, Object> verifyVersion2DoesHaveCompleteFirstConsume = creditCardManagerAuthorizationHandle.verifyVersion2DoesHaveCompleteFirstConsume(userIdStr, creditCardNumber, version);
		if(!CommonConstants.SUCCESS.equals(verifyVersion2DoesHaveCompleteFirstConsume.get(CommonConstants.RESP_CODE))){
			return verifyVersion2DoesHaveCompleteFirstConsume;
		}*/
		
		
		
//		验证是否有待执行的首笔消费任务
		ConsumeTaskPOJO firstConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType0ConsumeTaskPOJO(userIdStr,creditCardNumber,version);
//		必须先完成一笔消费任务
		if(firstConsumeTaskPOJO != null){
			CreditCardAccount creditCardAccount2;
			creditCardAccount2 = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userIdStr,creditCardNumber,version);
			LOG.info("==========================================首笔帐号信息:" + creditCardAccount2);
			if(creditCardAccount2==null){
				Map<String,Object> executeFirstConsumeTask = (Map<String, Object>) this.executeFirstConsumeTask(request, userIdStr, creditCardNumber,version);
				Map<String,Object> executeFirstRepaymentTask = null;
				if(CommonConstants.SUCCESS.equals(executeFirstConsumeTask.get(CommonConstants.RESP_CODE))){
					ConsumeTaskPOJO consumeTaskPOJO = (ConsumeTaskPOJO) executeFirstConsumeTask.get(CommonConstants.RESULT);
					Date nowTime = new Date();
					CreditCardAccount creditCardAccount = new CreditCardAccount();
					creditCardAccount.setUserId(userIdStr);
					creditCardAccount.setCreditCardNumber(creditCardNumber);
					creditCardAccount.setVersion(version);
					creditCardAccount.setPhone(phone);
					creditCardAccount.setBillDate(Integer.valueOf(billDate));
					creditCardAccount.setRepaymentDate(Integer.valueOf(repaymentDate));
					creditCardAccount.setCreditBlance(new BigDecimal(creditBlance));
					creditCardAccount.setLastUpdateTime(nowTime);
					creditCardAccount = creditCardAccountBusiness.save(creditCardAccount);
					creditCardAccountBusiness.updateCreditCardAccountAndVersion(userIdStr, creditCardNumber, consumeTaskPOJO.getConsumeTaskId(),0, consumeTaskPOJO.getAmount(),"首笔消费任务",version);
					
					executeFirstRepaymentTask = (Map<String, Object>) this.executeFirstRepaymentTask(request, userIdStr, creditCardNumber,version);
//					executeFirstRepaymentTask.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					return executeFirstRepaymentTask;
				}
				executeFirstConsumeTask.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				return executeFirstConsumeTask;
			}else if(creditCardAccount2.getBlance().compareTo(BigDecimal.ZERO) >0){
				firstConsumeTaskPOJO.setTaskStatus(1);
				firstConsumeTaskPOJO.setOrderStatus(1);
				consumeTaskPOJOBusiness.save(firstConsumeTaskPOJO);
				Map<String,Object> executeFirstRepaymentTask = (Map<String, Object>) this.executeFirstRepaymentTask(request, userIdStr, creditCardNumber,version);
				return executeFirstRepaymentTask;
			}
		}
		
//		验证是否有待执行的首笔还款任务
		firstRepaymentTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskStatus0AndTaskType0RepaymentTaskPOJO(userIdStr, creditCardNumber,version);
//		验证是否有已完成的首笔消费任务
		firstConsumeTaskPOJO = creditCardManagerAuthorizationHandle.verifyDoesHaveOrderStatus1AndTaskType0ConsumeTaskPOJO(userIdStr, creditCardNumber,version);
		if(firstConsumeTaskPOJO != null && firstRepaymentTaskPOJO!= null){
			CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userIdStr, creditCardNumber, version);
			if(creditCardAccount == null) {
				ConsumeTaskPOJO consumeTaskPOJO = consumeTaskPOJOBusiness.findByUserIdAndCreditCardNumberAndTaskTypeAndVersion(userIdStr, creditCardNumber, 0, version);
				Date nowTime = new Date();
				creditCardAccount = new CreditCardAccount();
				creditCardAccount.setUserId(userIdStr);
				creditCardAccount.setCreditCardNumber(creditCardNumber);
				creditCardAccount.setVersion(version);
				creditCardAccount.setPhone(phone);
				creditCardAccount.setBillDate(Integer.valueOf(billDate));
				creditCardAccount.setRepaymentDate(Integer.valueOf(repaymentDate));
				creditCardAccount.setCreditBlance(new BigDecimal(creditBlance));
				creditCardAccount.setLastUpdateTime(nowTime);
				creditCardAccount = creditCardAccountBusiness.save(creditCardAccount);
				creditCardAccountBusiness.updateCreditCardAccountAndVersion(userIdStr, creditCardNumber, consumeTaskPOJO.getConsumeTaskId(),0, consumeTaskPOJO.getAmount(),"首笔消费任务",version);
			}
			Map<String,Object> executeFirstRepaymentTask = (Map<String, Object>) this.executeFirstRepaymentTask(request, userIdStr, creditCardNumber,version);
			if(CommonConstants.SUCCESS.equals(executeFirstRepaymentTask.get(CommonConstants.RESP_CODE))){
				RepaymentTaskPOJO repaymentTaskPOJO = (RepaymentTaskPOJO) executeFirstRepaymentTask.get(CommonConstants.RESULT);
//				creditCardAccountBusiness.updateCreditCardAccount(userIdStr, creditCardNumber, repaymentTaskPOJO.getRepaymentTaskId(), 1, repaymentTaskPOJO.getRealAmount(), "首笔还款任务");
			}
			executeFirstRepaymentTask.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			return executeFirstRepaymentTask;
		}
		
		boolean verifyDoesHaveTaskType0Task = creditCardManagerAuthorizationHandle.verifyDoesHaveTaskType0Task(userIdStr,creditCardNumber,version);
		if (!verifyDoesHaveTaskType0Task) {
			return ResultWrap.err(LOG, CommonConstants.FALIED, "已有首笔验证任务,请稍后重试!");
		}
		
		Map<String, Object> userChannelRate = getUserChannelRate(userIdStr, brandId,version);
		if(!CommonConstants.SUCCESS.equals(userChannelRate.get(CommonConstants.RESP_CODE))){
			return userChannelRate;
		}
		resultJSONObject = (JSONObject) userChannelRate.get(CommonConstants.RESULT);
		
		String rateStr = resultJSONObject.getString("rate");
		String extraFeeStr = resultJSONObject.getString("extraFee");
		String withdrawFeeStr = resultJSONObject.getString("withdrawFee");
		BigDecimal serviceCharge = BigDecimal.ZERO;
		if(CardConstss.CARD_VERSION_1.equals(version)) {
			serviceCharge = new BigDecimal(extraFeeStr).add(new BigDecimal(withdrawFeeStr)).add(BigDecimal.valueOf(2)).setScale(2, BigDecimal.ROUND_UP);
		}else{
			serviceCharge = new BigDecimal(extraFeeStr).add(new BigDecimal(withdrawFeeStr)).setScale(2, BigDecimal.ROUND_UP);
		}
		BigDecimal rate = new BigDecimal(rateStr).setScale(4, BigDecimal.ROUND_UP);
		BigDecimal amount = BigDecimal.valueOf(firstMoney).add(serviceCharge).divide(BigDecimal.ONE.subtract(rate),2,BigDecimal.ROUND_UP);
		
		RepaymentTaskPOJO repaymentTaskPOJO = new RepaymentTaskPOJO();
		Date nowTime = new Date();
		Random random = new Random();
		repaymentTaskPOJO.setAmount(new BigDecimal(firstMoney));
		repaymentTaskPOJO.setRealAmount(new BigDecimal(firstMoney));
		repaymentTaskPOJO.setUserId(userIdStr);
		repaymentTaskPOJO.setChannelId(repaymentChannelId);
		repaymentTaskPOJO.setChannelTag(repaymentChannelTag);
		repaymentTaskPOJO.setServiceCharge(serviceCharge);
		repaymentTaskPOJO.setTotalServiceCharge(amount.subtract(BigDecimal.valueOf(firstMoney)));
		repaymentTaskPOJO.setRate(rate);
		repaymentTaskPOJO.setVersion(version);
		repaymentTaskPOJO.setRepaymentTaskId(DateUtil.getDateStringConvert(new String(), nowTime,"yyyyMMddHHSSS")+random.nextInt(9)+random.nextInt(9)+random.nextInt(9)+random.nextInt(9)+"1");
		repaymentTaskPOJO.setCreditCardNumber(creditCardNumber);
		repaymentTaskPOJO.setDescription("尾号" + creditCardNumber.substring(creditCardNumber.length()-4) + "首笔还款任务");
		repaymentTaskPOJO.setCreateTime(DateUtil.getDateStringConvert(new String(), nowTime,"yyyy-MM-dd HH:ss:mm"));
		repaymentTaskPOJO.setExecuteDate(DateUtil.getDateStringConvert(new String(), nowTime,"yyyy-MM-dd"));
		repaymentTaskPOJO.setExecuteDateTime(DateUtil.getDateStringConvert(new String(), nowTime,"yyyy-MM-dd HH:ss:mm"));
		repaymentTaskPOJO.setTaskType(0);
		ConsumeTaskPOJO consumeTaskPOJO = new ConsumeTaskPOJO();
		BeanUtils.copyProperties(repaymentTaskPOJO, consumeTaskPOJO);
		consumeTaskPOJO.setAmount(BigDecimal.valueOf(firstMoney));
		consumeTaskPOJO.setRealAmount(amount);
		consumeTaskPOJO.setChannelId(consumeChannelId);
		consumeTaskPOJO.setChannelTag(consumeChannelTag);
		consumeTaskPOJO.setVersion(version);
		consumeTaskPOJO.setServiceCharge(repaymentTaskPOJO.getTotalServiceCharge());
		consumeTaskPOJO.setConsumeTaskId(Long.valueOf(repaymentTaskPOJO.getRepaymentTaskId())+1+"");
		consumeTaskPOJO.setDescription("尾号" + creditCardNumber.substring(creditCardNumber.length()-4) + "首笔消费任务");
		consumeTaskPOJO.setRepaymentTaskId(repaymentTaskPOJO.getRepaymentTaskId());
		consumeTaskPOJO.setCreateTime(DateUtil.getDateStringConvert(new String(), nowTime,"yyyy-MM-dd HH:ss:mm"));
		
		repaymentTaskPOJOBusiness.saveReapymentTaskAndConsumeTask(repaymentTaskPOJO,consumeTaskPOJO);
		
		Map<String, Object> consumeMap;
		try {
			consumeMap = (Map<String, Object>) this.executeFirstConsumeTask(request, userIdStr, creditCardNumber, version);
		} catch (Exception e) {
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE,"等待银行扣款,请稍后!");
			return map;
		}
		if(!CommonConstants.SUCCESS.equals(consumeMap.get(CommonConstants.RESP_CODE))){
			if(CardConstss.WAIT_NOTIFY.equals(consumeMap.get(CommonConstants.RESP_CODE))) {
				return consumeMap;
			}else {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, consumeMap.containsKey(CommonConstants.RESP_MESSAGE)?((String)consumeMap.get(CommonConstants.RESP_MESSAGE)).replaceAll("[0-9]", "").replaceAll("[\\[|\\]|\\.|\\:]", "").replaceAll("[A-Za-z]", ""):"消费失败!");
				return map;
			}
		}
		consumeTaskPOJO = consumeTaskPOJOBusiness.findByConsumeTaskId(consumeTaskPOJO.getConsumeTaskId());
		consumeTaskPOJO.setReturnMessage("消费成功");
		consumeTaskPOJO.setTaskStatus(1);
		consumeTaskPOJO.setOrderStatus(1);
		consumeTaskPOJO = consumeTaskPOJOBusiness.save(consumeTaskPOJO);
		
		nowTime = new Date();
		CreditCardAccount creditCardAccount = null;
		creditCardAccount = creditCardAccountBusiness.findByCreditCardNumberAndVersion(creditCardNumber, version);
		if (creditCardAccount == null) {
			creditCardAccount = new CreditCardAccount();
		}
		creditCardAccount.setUserId(userIdStr);
		creditCardAccount.setCreditCardNumber(creditCardNumber);
		creditCardAccount.setVersion(version);
		creditCardAccount.setPhone(phone);
//		creditCardAccount.setBlance(creditCardAccount.getBlance().add(consumeTaskPOJO.getAmount()));
		creditCardAccount.setBillDate(Integer.valueOf(billDate));
		creditCardAccount.setRepaymentDate(Integer.valueOf(repaymentDate));
		creditCardAccount.setCreditBlance(new BigDecimal(creditBlance));
		creditCardAccount.setLastUpdateTime(nowTime);
		creditCardAccount = creditCardAccountBusiness.save(creditCardAccount);
		creditCardAccountBusiness.updateCreditCardAccountAndVersion(userIdStr, creditCardNumber, consumeTaskPOJO.getConsumeTaskId(),0, consumeTaskPOJO.getAmount(),"首笔消费任务",version);
//		creditCardAccountHistoryBusiness.createNewHistory(0, amount, consumeTaskPOJO.getConsumeTaskId(), creditCardAccount.getId(), creditCardAccount.getBlance(), "首笔消费任务");
		
		Map<String, Object> repaymentMap;
		try {
			repaymentMap = (Map<String, Object>) this.executeFirstRepaymentTask(request, userIdStr, creditCardNumber, version);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE,"等待出款中,请等待!");
			return map;
		}
		if(!CommonConstants.SUCCESS.equals(repaymentMap.get(CommonConstants.RESP_CODE))){
			return repaymentMap;
		}
		repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskPOJO.getRepaymentTaskId());
		repaymentTaskPOJO.setReturnMessage("还款成功!");
		repaymentTaskPOJO.setTaskStatus(1);
		repaymentTaskPOJO.setOrderStatus(1);
		repaymentTaskPOJO = repaymentTaskPOJOBusiness.updateTaskStatusAndOrderStatusAndReturnMessageByRepaymentTaskId(1, 1, "还款成功!", repaymentTaskPOJO.getRepaymentTaskId());
		creditCardAccountBusiness.updateCreditCardAccountAndVersion(userIdStr, creditCardNumber,repaymentTaskPOJO.getRepaymentTaskId(), 4, repaymentTaskPOJO.getRealAmount(), "首笔还款成功减少冻结余额",version);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "首笔任务完成,可进入生成计划!");
		return map;
	}
	
//	修改任务状态回调
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/update/taskstatus/by/ordercode")
	public @ResponseBody Object updateTaskStatusByOrderCode(HttpServletRequest request,
			@RequestParam(value="orderCode")String orderCode,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		LOG.info("回调订单号================================:" + orderCode);
		Map<String,Object> map = new HashMap<>();
		Map<String, Object> verifyStringFiledIsNullMap = creditCardManagerAuthorizationHandle.verifyStringFiledIsNull(orderCode);
		if(!CommonConstants.SUCCESS.equals(verifyStringFiledIsNullMap.get(CommonConstants.RESP_CODE))){
			return verifyStringFiledIsNullMap;
		}
		LinkedMultiValueMap<String,String> requestEntity = new LinkedMultiValueMap<String,String>();
		requestEntity.add("order_code", orderCode);
		Map<String, Object> restTemplateDoPost = util.restTemplateDoPost("transactionclear", "/v1.0/transactionclear/payment/query/ordercode", requestEntity);
		if(!CommonConstants.SUCCESS.equals(restTemplateDoPost.get(CommonConstants.RESP_CODE))){
			return restTemplateDoPost;
		}
		
		JSONObject resultJSON = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
		String creditCardNumber = resultJSON.getString("bankcard");
		String realAmountStr = resultJSON.getString("amount");
		String phone = resultJSON.getString("phone");
		String orderType = resultJSON.getString("type");
		
		
		
		RepaymentTaskPOJO repaymentTaskPOJO2 = null;
		ConsumeTaskPOJO consumeTaskPOJO2 = null;
		if(CommonConstants.ORDER_TYPE_REPAYMENT.equals(orderType)){
			repaymentTaskPOJO2 = repaymentTaskPOJOBusiness.findByRepaymentTaskId(orderCode);
		}
		if (CommonConstants.ORDER_TYPE_CONSUME.equals(orderType)) {
			consumeTaskPOJO2 = consumeTaskPOJOBusiness.findByConsumeTaskId(orderCode);
		}
		
		
		RepaymentTaskPOJO repaymentTaskPOJO0 = null;
		ConsumeTaskPOJO consumeTaskPOJO0 = null;
		if(repaymentTaskPOJO2 == null && CommonConstants.ORDER_TYPE_REPAYMENT.equals(orderType)){
			repaymentTaskPOJO0 = repaymentTaskPOJOBusiness.findByCreditCardNumberAndTaskTypeAndVersion(creditCardNumber,0,version);
		}
		if(consumeTaskPOJO2 == null && CommonConstants.ORDER_TYPE_CONSUME.equals(orderType)){
			consumeTaskPOJO0 = consumeTaskPOJOBusiness.findByCreditCardNumberAndTaskTypeAndVersion(creditCardNumber,0,version);
		}
		
		RepaymentTaskPOJO repaymentTaskPOJO = null;
		ConsumeTaskPOJO consumeTaskPOJO = null;
		if(repaymentTaskPOJO == null && repaymentTaskPOJO0!=null && repaymentTaskPOJO0.getOrderStatus().intValue()!=1){
			repaymentTaskPOJO = repaymentTaskPOJO0;
		}else if(repaymentTaskPOJO2 !=null){
			repaymentTaskPOJO = repaymentTaskPOJO2;
		}
		
		if(consumeTaskPOJO == null && consumeTaskPOJO0!=null && consumeTaskPOJO0.getOrderStatus().intValue() !=1){
			consumeTaskPOJO = consumeTaskPOJO0;
		}else if(consumeTaskPOJO2!=null){
			consumeTaskPOJO = consumeTaskPOJO2;
		}
		
		if(repaymentTaskPOJO!=null && repaymentTaskPOJO.getOrderStatus().intValue()!=1){
			repaymentTaskPOJO.setTaskStatus(1);
			repaymentTaskPOJO.setOrderStatus(1);
			repaymentTaskPOJO.setOrderCode(orderCode);
			repaymentTaskPOJO.setReturnMessage("还款成功");
			repaymentTaskPOJO.setRealAmount(new BigDecimal(realAmountStr));
			BigDecimal realAmount = repaymentTaskPOJO.getAmount();
			if(repaymentTaskPOJO.getRealAmount().compareTo(repaymentTaskPOJO.getAmount())!= 0&&repaymentTaskPOJO.getTaskType().intValue() != 1 && repaymentTaskPOJO.getTaskType() != 0){
				realAmount = repaymentTaskPOJO.getRealAmount();
				if(BigDecimal.ZERO.compareTo(realAmount) >= 0){
					realAmount = new BigDecimal(realAmountStr);
					creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(),repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(),1,realAmount, "增加冻结余额",version);
				}
			}
			creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(),repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(),4,realAmount, "还款成功减少冻结余额",version);
			repaymentTaskPOJO = repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
			LOG.info("回调修改还款任务成功===================" + repaymentTaskPOJO);
		}
		if(consumeTaskPOJO!=null && consumeTaskPOJO.getOrderStatus().intValue() !=1){
			consumeTaskPOJO.setReturnMessage("消费成功");
			consumeTaskPOJO.setTaskStatus(1);
			consumeTaskPOJO.setOrderStatus(1);
			consumeTaskPOJO.setOrderCode(orderCode);
			consumeTaskPOJO = consumeTaskPOJOBusiness.save(consumeTaskPOJO);

			if(consumeTaskPOJO.getTaskType().intValue() == 0) {
				CreditCardAccount creditCardAccount2 = creditCardAccountBusiness.findByCreditCardNumberAndVersion(creditCardNumber, version);
				if (creditCardAccount2 == null) {
					int billDate = 0;
					int repaymentDate = 0;
					String creditBlance = "0";
					try {
						JSONObject userBankInfo = this.getUserBankInfo(consumeTaskPOJO.getUserId(), creditCardNumber);
						userBankInfo = userBankInfo.getJSONObject(CommonConstants.RESULT);
						billDate = userBankInfo.getInt("billDay");
						repaymentDate = userBankInfo.getInt("repaymentDay");
						creditBlance = userBankInfo.getString("creditBlance");
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					Date nowTime = new Date();
					CreditCardAccount creditCardAccount = new CreditCardAccount();
					creditCardAccount.setUserId(consumeTaskPOJO.getUserId());
					creditCardAccount.setCreditCardNumber(creditCardNumber);
					creditCardAccount.setVersion(version);
					creditCardAccount.setPhone(phone);
					creditCardAccount.setBillDate(Integer.valueOf(billDate));
					creditCardAccount.setRepaymentDate(Integer.valueOf(repaymentDate));
					creditCardAccount.setCreditBlance(new BigDecimal(creditBlance));
					creditCardAccount.setLastUpdateTime(nowTime);
					creditCardAccount = creditCardAccountBusiness.save(creditCardAccount);
				}
				creditCardAccountBusiness.updateCreditCardAccountAndVersion(consumeTaskPOJO.getUserId(), creditCardNumber, consumeTaskPOJO.getConsumeTaskId(),0, consumeTaskPOJO.getAmount(),"首笔消费任务",version);
				this.executeFirstRepaymentTask(request, consumeTaskPOJO.getUserId(), creditCardNumber, version);
			}else {
				creditCardAccountBusiness.updateCreditCardAccountAndVersion(consumeTaskPOJO.getUserId(),consumeTaskPOJO.getCreditCardNumber(), consumeTaskPOJO.getConsumeTaskId(), 0,consumeTaskPOJO.getAmount(), "消费成功",version);
			}
			LOG.info("回调修改消费任务成功===================" + consumeTaskPOJO);
		}
		
		map.put("repaymentTaskPOJO",repaymentTaskPOJO );
		map.put("consumeTaskPOJO",consumeTaskPOJO );
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "修改任务状态成功");
		return map;
	}
	
	
	private JSONObject getUserBankInfo(String userId,String creditCardNumber) {
		String url = "http://user/v1.0/user/bank/find/bankphone";
		LinkedMultiValueMap<String,String> requestEntity = new LinkedMultiValueMap<String,String>();
		requestEntity.add("userId", userId);
		requestEntity.add("cardNo",creditCardNumber);
		String resultString = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject resultJSON = JSONObject.fromObject(resultString);
		LOG.info(url + "======" + resultJSON);
		return resultJSON;
	}

	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/go/to/first/repaymenttask")
	public @ResponseBody Object executeFirstRepaymentTask(HttpServletRequest request,
			@RequestParam(value="userId")String userId,
			@RequestParam(value="creditCardNumber")String creditCardNumber,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object>map = new HashMap<>();
		RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByTaskType0AndTaskStatus0RepaymentTaskPOJOAndVersion(userId,creditCardNumber,version);
		if(repaymentTaskPOJO==null){
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您没有待执行的还款任务!");
			return map;
		}
		Map<String, Object> executeRepaymentTaskMap = null;
		CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userId, creditCardNumber,version);
		try {
			if(creditCardAccount.getBlance().compareTo(repaymentTaskPOJO.getAmount()) >= 0){
				executeRepaymentTaskMap = repaymentExecutor.executeRepaymentTask(repaymentTaskPOJO);
			}else{
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "您有待完成的首笔还款任务,请等待完成后再点击,如果等待时间过长,请联系管理员!");
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskPOJO.getRepaymentTaskId());
			repaymentTaskPOJO.setErrorMessage(e.toString().substring(0, e.toString().length()>=250?250:e.toString().length()));
			repaymentTaskPOJO.setTaskStatus(1);
			repaymentTaskPOJO.setReturnMessage("等待出款中,请等待!");
			repaymentTaskPOJO.setOrderStatus(4);
			repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "等待出款中,请稍后");
			return map;
		}
		repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskPOJO.getRepaymentTaskId());
		if(!CommonConstants.SUCCESS.equals(executeRepaymentTaskMap.get(CommonConstants.RESP_CODE))){
			if(CardConstss.WAIT_NOTIFY.equals(executeRepaymentTaskMap.get(CommonConstants.RESP_CODE))){
				repaymentTaskPOJO.setTaskStatus(1);
				repaymentTaskPOJO.setReturnMessage("等待出款中,请等待!");
				repaymentTaskPOJO.setOrderStatus(4);
				repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "等待出款中,请稍后");
			}else{
				repaymentTaskPOJO.setErrorMessage(executeRepaymentTaskMap.containsKey(CommonConstants.RESP_MESSAGE)?(String) executeRepaymentTaskMap.get(CommonConstants.RESP_MESSAGE):"还款失败!");
				repaymentTaskPOJO.setReturnMessage("还款失败!");
				repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
				creditCardAccountBusiness.updateCreditCardAccountAndVersion(userId, creditCardNumber,repaymentTaskPOJO.getRepaymentTaskId(), 3, repaymentTaskPOJO.getRealAmount(),"首笔还款失败增加余额",version);
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, executeRepaymentTaskMap.containsKey(CommonConstants.RESP_MESSAGE)?executeRepaymentTaskMap.get(CommonConstants.RESP_MESSAGE):"还款失败!");
			}
			return map;
		}
		repaymentTaskPOJO.setReturnMessage("还款成功!");
		repaymentTaskPOJO.setTaskStatus(1);
		repaymentTaskPOJO.setOrderStatus(1);
		repaymentTaskPOJO = repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
		creditCardAccountBusiness.updateCreditCardAccountAndVersion(userId, creditCardNumber,repaymentTaskPOJO.getRepaymentTaskId(), 4, repaymentTaskPOJO.getRealAmount(), "首笔还款成功减少冻结余额",version);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "首笔还款任务成功,请点击进入生成计划页面!");
		map.put(CommonConstants.RESULT, repaymentTaskPOJO);
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/go/to/first/consumetask")
	public @ResponseBody Object executeFirstConsumeTask(HttpServletRequest request,
			@RequestParam(value="userId")String userId,
			@RequestParam(value="creditCardNumber")String creditCardNumber,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object>map = new HashMap<>();
		ConsumeTaskPOJO consumeTaskPOJO = consumeTaskPOJOBusiness.findByTaskType0AndTaskStatus0ConsumeTaskPOJOAndVersion(userId,creditCardNumber,version);
		if(consumeTaskPOJO==null){
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您没有待执行的消费任务!");
			return map;
		}
		Map<String, Object> executeRepaymentTaskMap;
		CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userId, creditCardNumber,version);
		try {
			if(creditCardAccount==null){
				executeRepaymentTaskMap = consumeExecutor.executeConsumeTask(consumeTaskPOJO);
			}else{
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "等待消费执行完毕,请稍后重试");
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			consumeTaskPOJO = consumeTaskPOJOBusiness.findByConsumeTaskId(consumeTaskPOJO.getConsumeTaskId());
			consumeTaskPOJO.setTaskStatus(1);
			consumeTaskPOJO.setOrderStatus(4);
			consumeTaskPOJO.setReturnMessage("等待银行扣款,请稍后!");
			consumeTaskPOJO = consumeTaskPOJOBusiness.save(consumeTaskPOJO);
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "等待银行扣款中,请稍后!");
			return map;
		}
		consumeTaskPOJO = consumeTaskPOJOBusiness.findByConsumeTaskId(consumeTaskPOJO.getConsumeTaskId());
		if(!CommonConstants.SUCCESS.equals(executeRepaymentTaskMap.get(CommonConstants.RESP_CODE))){
			if (CardConstss.WAIT_NOTIFY.equals(executeRepaymentTaskMap.get(CommonConstants.RESP_CODE))) {
				consumeTaskPOJO.setTaskStatus(1);
				consumeTaskPOJO.setOrderStatus(4);
				consumeTaskPOJO.setReturnMessage("等待银行扣款,请稍后!");
				consumeTaskPOJO = consumeTaskPOJOBusiness.save(consumeTaskPOJO);
			}
			return executeRepaymentTaskMap;
		}
		consumeTaskPOJO.setTaskStatus(1);
		consumeTaskPOJO.setOrderStatus(1);
		consumeTaskPOJO.setReturnMessage("消费成功!");
		consumeTaskPOJOBusiness.save(consumeTaskPOJO);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "首笔消费成功,请继续点击进行还款操作!");
		map.put(CommonConstants.RESULT, consumeTaskPOJO);
		return map;
	}
	
	private Map<String,Object> getUserChannelRate(String userId,String brandId,String version){
		Map<String,Object> map = new HashMap<>();
		String channelId = null;
		CreditCardManagerConfig creditCardManagerConfigs = creditCardManagerConfigBusiness.findByVersion(version);
//		LOG.info(creditCardManagerConfigs.toString());
		if(creditCardManagerConfigs != null){
			channelId = creditCardManagerConfigs.getChannelId();
		}else{
			return ResultWrap.init(CommonConstants.FALIED, "无用户费率!");
		}
		
		LinkedMultiValueMap<String,String> requestEntity = new LinkedMultiValueMap<String,String>();
		requestEntity.add("user_id",userId);
		requestEntity.add("channel_id", channelId);
		Map<String, Object> restTemplateDoPost = util.restTemplateDoPost("user", "/v1.0/user/channel/rate/query/userid", requestEntity);
		if(!CommonConstants.SUCCESS.equals(restTemplateDoPost.get(CommonConstants.RESP_CODE))){
			return restTemplateDoPost;
		}
		JSONObject resultJSONObject = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, resultJSONObject);
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/test/saveconsume")
	public @ResponseBody Object executeFirstConsumeTask(HttpServletRequest request
			){
//		List<ConsumeTaskPOJO> findByConsumeTaskId = consumeTaskPOJOBusiness.findByTaskTypeAndTaskStatusAndVersionAndExecuteDate(2,4,"1","2018-05-30");
//		for (ConsumeTaskPOJO consumeTaskPOJO :findByConsumeTaskId) {
//			String consumeTaskId = consumeTaskPOJO.getConsumeTaskId();
//			if ("3".equals(consumeTaskId.substring(consumeTaskId.length()-1))) {
//				consumeTaskId = consumeTaskId.substring(0, consumeTaskId.length()-1) + "2";
//				ConsumeTaskPOJO findByConsumeTaskId2 = consumeTaskPOJOBusiness.findByConsumeTaskId(consumeTaskId);
//				if (findByConsumeTaskId2 != null && findByConsumeTaskId2.getOrderStatus().intValue() == 1) {
//					consumeTaskPOJO.setTaskStatus(0);
//					consumeTaskPOJOBusiness.save(consumeTaskPOJO);
//					System.out.println("修改成功====" + consumeTaskPOJO);
//				}
//			}
//		}
		
//		List<RepaymentTaskPOJO> repaymentTaskPOJOs = repaymentTaskPOJOBusiness.findByTaskTypeAndTaskStatusAndVersionAndExecuteDate(2,4,"1","2018-05-30");
//		for (RepaymentTaskPOJO repaymentTaskPOJO:repaymentTaskPOJOs) {
//			String repaymentTaskId = repaymentTaskPOJO.getRepaymentTaskId();
//			repaymentTaskId = repaymentTaskId.substring(0, repaymentTaskId.length()-1) + "2";
//			ConsumeTaskPOJO findByConsumeTaskId2 = consumeTaskPOJOBusiness.findByConsumeTaskId(repaymentTaskId);
//			if (findByConsumeTaskId2 != null && findByConsumeTaskId2.getOrderStatus().intValue() == 1) {
//				repaymentTaskPOJO.setTaskStatus(0);
//				repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
//				System.out.println("修改成功====" + repaymentTaskPOJO);
//			}
//		}
		JSONObject orderStatus = null;
		orderStatus = baseExecutor.getOrderStatusByVersion("201805311841764671", CommonConstants.ORDER_TYPE_REPAYMENT, "3");
		return orderStatus;
	}
			
}
